babylon.1.14-RC-debug.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.multiplyInPlace = function (otherVector) {
  238. this.x *= otherVector.x;
  239. this.y *= otherVector.y;
  240. };
  241. Vector2.prototype.multiply = function (otherVector) {
  242. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  243. };
  244. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  245. result.x = this.x * otherVector.x;
  246. result.y = this.y * otherVector.y;
  247. };
  248. Vector2.prototype.multiplyByFloats = function (x, y) {
  249. return new Vector2(this.x * x, this.y * y);
  250. };
  251. Vector2.prototype.divide = function (otherVector) {
  252. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  253. };
  254. Vector2.prototype.divideToRef = function (otherVector, result) {
  255. result.x = this.x / otherVector.x;
  256. result.y = this.y / otherVector.y;
  257. };
  258. Vector2.prototype.negate = function () {
  259. return new Vector2(-this.x, -this.y);
  260. };
  261. Vector2.prototype.scaleInPlace = function (scale) {
  262. this.x *= scale;
  263. this.y *= scale;
  264. };
  265. Vector2.prototype.scale = function (scale) {
  266. return new Vector2(this.x * scale, this.y * scale);
  267. };
  268. Vector2.prototype.equals = function (otherVector) {
  269. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  270. };
  271. Vector2.prototype.length = function () {
  272. return Math.sqrt(this.x * this.x + this.y * this.y);
  273. };
  274. Vector2.prototype.lengthSquared = function () {
  275. return (this.x * this.x + this.y * this.y);
  276. };
  277. Vector2.prototype.normalize = function () {
  278. var len = this.length();
  279. if (len === 0)
  280. return;
  281. var num = 1.0 / len;
  282. this.x *= num;
  283. this.y *= num;
  284. };
  285. Vector2.prototype.clone = function () {
  286. return new Vector2(this.x, this.y);
  287. };
  288. Vector2.Zero = function () {
  289. return new Vector2(0, 0);
  290. };
  291. Vector2.FromArray = function (array, offset) {
  292. if (!offset) {
  293. offset = 0;
  294. }
  295. return new Vector2(array[offset], array[offset + 1]);
  296. };
  297. Vector2.FromArrayToRef = function (array, offset, result) {
  298. result.x = array[offset];
  299. result.y = array[offset + 1];
  300. };
  301. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  302. var squared = amount * amount;
  303. var cubed = amount * squared;
  304. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  305. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  306. return new Vector2(x, y);
  307. };
  308. Vector2.Clamp = function (value, min, max) {
  309. var x = value.x;
  310. x = (x > max.x) ? max.x : x;
  311. x = (x < min.x) ? min.x : x;
  312. var y = value.y;
  313. y = (y > max.y) ? max.y : y;
  314. y = (y < min.y) ? min.y : y;
  315. return new Vector2(x, y);
  316. };
  317. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  318. var squared = amount * amount;
  319. var cubed = amount * squared;
  320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  322. var part3 = (cubed - (2.0 * squared)) + amount;
  323. var part4 = cubed - squared;
  324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  326. return new Vector2(x, y);
  327. };
  328. Vector2.Lerp = function (start, end, amount) {
  329. var x = start.x + ((end.x - start.x) * amount);
  330. var y = start.y + ((end.y - start.y) * amount);
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Dot = function (left, right) {
  334. return left.x * right.x + left.y * right.y;
  335. };
  336. Vector2.Normalize = function (vector) {
  337. var newVector = vector.clone();
  338. newVector.normalize();
  339. return newVector;
  340. };
  341. Vector2.Minimize = function (left, right) {
  342. var x = (left.x < right.x) ? left.x : right.x;
  343. var y = (left.y < right.y) ? left.y : right.y;
  344. return new Vector2(x, y);
  345. };
  346. Vector2.Maximize = function (left, right) {
  347. var x = (left.x > right.x) ? left.x : right.x;
  348. var y = (left.y > right.y) ? left.y : right.y;
  349. return new Vector2(x, y);
  350. };
  351. Vector2.Transform = function (vector, transformation) {
  352. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  353. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Distance = function (value1, value2) {
  357. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  358. };
  359. Vector2.DistanceSquared = function (value1, value2) {
  360. var x = value1.x - value2.x;
  361. var y = value1.y - value2.y;
  362. return (x * x) + (y * y);
  363. };
  364. return Vector2;
  365. })();
  366. BABYLON.Vector2 = Vector2;
  367. var Vector3 = (function () {
  368. function Vector3(x, y, z) {
  369. this.x = x;
  370. this.y = y;
  371. this.z = z;
  372. }
  373. Vector3.prototype.toString = function () {
  374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  375. };
  376. Vector3.prototype.asArray = function () {
  377. var result = [];
  378. this.toArray(result, 0);
  379. return result;
  380. };
  381. Vector3.prototype.toArray = function (array, index) {
  382. if (index === undefined) {
  383. index = 0;
  384. }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. array[index + 2] = this.z;
  388. };
  389. Vector3.prototype.addInPlace = function (otherVector) {
  390. this.x += otherVector.x;
  391. this.y += otherVector.y;
  392. this.z += otherVector.z;
  393. };
  394. Vector3.prototype.add = function (otherVector) {
  395. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  396. };
  397. Vector3.prototype.addToRef = function (otherVector, result) {
  398. result.x = this.x + otherVector.x;
  399. result.y = this.y + otherVector.y;
  400. result.z = this.z + otherVector.z;
  401. };
  402. Vector3.prototype.subtractInPlace = function (otherVector) {
  403. this.x -= otherVector.x;
  404. this.y -= otherVector.y;
  405. this.z -= otherVector.z;
  406. };
  407. Vector3.prototype.subtract = function (otherVector) {
  408. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  409. };
  410. Vector3.prototype.subtractToRef = function (otherVector, result) {
  411. result.x = this.x - otherVector.x;
  412. result.y = this.y - otherVector.y;
  413. result.z = this.z - otherVector.z;
  414. };
  415. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  416. return new Vector3(this.x - x, this.y - y, this.z - z);
  417. };
  418. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  419. result.x = this.x - x;
  420. result.y = this.y - y;
  421. result.z = this.z - z;
  422. };
  423. Vector3.prototype.negate = function () {
  424. return new Vector3(-this.x, -this.y, -this.z);
  425. };
  426. Vector3.prototype.scaleInPlace = function (scale) {
  427. this.x *= scale;
  428. this.y *= scale;
  429. this.z *= scale;
  430. };
  431. Vector3.prototype.scale = function (scale) {
  432. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  433. };
  434. Vector3.prototype.scaleToRef = function (scale, result) {
  435. result.x = this.x * scale;
  436. result.y = this.y * scale;
  437. result.z = this.z * scale;
  438. };
  439. Vector3.prototype.equals = function (otherVector) {
  440. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  441. };
  442. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  443. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  444. };
  445. Vector3.prototype.equalsToFloats = function (x, y, z) {
  446. return this.x === x && this.y === y && this.z === z;
  447. };
  448. Vector3.prototype.multiplyInPlace = function (otherVector) {
  449. this.x *= otherVector.x;
  450. this.y *= otherVector.y;
  451. this.z *= otherVector.z;
  452. };
  453. Vector3.prototype.multiply = function (otherVector) {
  454. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  455. };
  456. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  457. result.x = this.x * otherVector.x;
  458. result.y = this.y * otherVector.y;
  459. result.z = this.z * otherVector.z;
  460. };
  461. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  462. return new Vector3(this.x * x, this.y * y, this.z * z);
  463. };
  464. Vector3.prototype.divide = function (otherVector) {
  465. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  466. };
  467. Vector3.prototype.divideToRef = function (otherVector, result) {
  468. result.x = this.x / otherVector.x;
  469. result.y = this.y / otherVector.y;
  470. result.z = this.z / otherVector.z;
  471. };
  472. Vector3.prototype.MinimizeInPlace = function (other) {
  473. if (other.x < this.x)
  474. this.x = other.x;
  475. if (other.y < this.y)
  476. this.y = other.y;
  477. if (other.z < this.z)
  478. this.z = other.z;
  479. };
  480. Vector3.prototype.MaximizeInPlace = function (other) {
  481. if (other.x > this.x)
  482. this.x = other.x;
  483. if (other.y > this.y)
  484. this.y = other.y;
  485. if (other.z > this.z)
  486. this.z = other.z;
  487. };
  488. Vector3.prototype.length = function () {
  489. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  490. };
  491. Vector3.prototype.lengthSquared = function () {
  492. return (this.x * this.x + this.y * this.y + this.z * this.z);
  493. };
  494. Vector3.prototype.normalize = function () {
  495. var len = this.length();
  496. if (len === 0)
  497. return;
  498. var num = 1.0 / len;
  499. this.x *= num;
  500. this.y *= num;
  501. this.z *= num;
  502. };
  503. Vector3.prototype.clone = function () {
  504. return new Vector3(this.x, this.y, this.z);
  505. };
  506. Vector3.prototype.copyFrom = function (source) {
  507. this.x = source.x;
  508. this.y = source.y;
  509. this.z = source.z;
  510. };
  511. Vector3.prototype.copyFromFloats = function (x, y, z) {
  512. this.x = x;
  513. this.y = y;
  514. this.z = z;
  515. };
  516. Vector3.FromArray = function (array, offset) {
  517. if (!offset) {
  518. offset = 0;
  519. }
  520. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  521. };
  522. Vector3.FromArrayToRef = function (array, offset, result) {
  523. result.x = array[offset];
  524. result.y = array[offset + 1];
  525. result.z = array[offset + 2];
  526. };
  527. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  528. result.x = array[offset];
  529. result.y = array[offset + 1];
  530. result.z = array[offset + 2];
  531. };
  532. Vector3.FromFloatsToRef = function (x, y, z, result) {
  533. result.x = x;
  534. result.y = y;
  535. result.z = z;
  536. };
  537. Vector3.Zero = function () {
  538. return new Vector3(0, 0, 0);
  539. };
  540. Vector3.Up = function () {
  541. return new Vector3(0, 1.0, 0);
  542. };
  543. Vector3.TransformCoordinates = function (vector, transformation) {
  544. var result = Vector3.Zero();
  545. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  546. return result;
  547. };
  548. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  552. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  553. result.x = x / w;
  554. result.y = y / w;
  555. result.z = z / w;
  556. };
  557. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  558. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  559. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  560. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  561. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  562. result.x = rx / rw;
  563. result.y = ry / rw;
  564. result.z = rz / rw;
  565. };
  566. Vector3.TransformNormal = function (vector, transformation) {
  567. var result = Vector3.Zero();
  568. Vector3.TransformNormalToRef(vector, transformation, result);
  569. return result;
  570. };
  571. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  572. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  573. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  574. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  575. };
  576. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  577. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  578. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  579. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  580. };
  581. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  582. var squared = amount * amount;
  583. var cubed = amount * squared;
  584. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  586. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  587. return new Vector3(x, y, z);
  588. };
  589. Vector3.Clamp = function (value, min, max) {
  590. var x = value.x;
  591. x = (x > max.x) ? max.x : x;
  592. x = (x < min.x) ? min.x : x;
  593. var y = value.y;
  594. y = (y > max.y) ? max.y : y;
  595. y = (y < min.y) ? min.y : y;
  596. var z = value.z;
  597. z = (z > max.z) ? max.z : z;
  598. z = (z < min.z) ? min.z : z;
  599. return new Vector3(x, y, z);
  600. };
  601. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  602. var squared = amount * amount;
  603. var cubed = amount * squared;
  604. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  605. var part2 = (-2.0 * cubed) + (3.0 * squared);
  606. var part3 = (cubed - (2.0 * squared)) + amount;
  607. var part4 = cubed - squared;
  608. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  609. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  610. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  611. return new Vector3(x, y, z);
  612. };
  613. Vector3.Lerp = function (start, end, amount) {
  614. var x = start.x + ((end.x - start.x) * amount);
  615. var y = start.y + ((end.y - start.y) * amount);
  616. var z = start.z + ((end.z - start.z) * amount);
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Dot = function (left, right) {
  620. return (left.x * right.x + left.y * right.y + left.z * right.z);
  621. };
  622. Vector3.Cross = function (left, right) {
  623. var result = Vector3.Zero();
  624. Vector3.CrossToRef(left, right, result);
  625. return result;
  626. };
  627. Vector3.CrossToRef = function (left, right, result) {
  628. result.x = left.y * right.z - left.z * right.y;
  629. result.y = left.z * right.x - left.x * right.z;
  630. result.z = left.x * right.y - left.y * right.x;
  631. };
  632. Vector3.Normalize = function (vector) {
  633. var result = Vector3.Zero();
  634. Vector3.NormalizeToRef(vector, result);
  635. return result;
  636. };
  637. Vector3.NormalizeToRef = function (vector, result) {
  638. result.copyFrom(vector);
  639. result.normalize();
  640. };
  641. Vector3.Project = function (vector, world, transform, viewport) {
  642. var cw = viewport.width;
  643. var ch = viewport.height;
  644. var cx = viewport.x;
  645. var cy = viewport.y;
  646. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  647. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  648. return Vector3.TransformCoordinates(vector, finalMatrix);
  649. };
  650. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  651. var matrix = world.multiply(view).multiply(projection);
  652. matrix.invert();
  653. source.x = source.x / viewportWidth * 2 - 1;
  654. source.y = -(source.y / viewportHeight * 2 - 1);
  655. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  656. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  657. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  658. vector = vector.scale(1.0 / num);
  659. }
  660. return vector;
  661. };
  662. Vector3.Minimize = function (left, right) {
  663. var min = left.clone();
  664. min.MinimizeInPlace(right);
  665. return min;
  666. };
  667. Vector3.Maximize = function (left, right) {
  668. var max = left.clone();
  669. max.MaximizeInPlace(right);
  670. return max;
  671. };
  672. Vector3.Distance = function (value1, value2) {
  673. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  674. };
  675. Vector3.DistanceSquared = function (value1, value2) {
  676. var x = value1.x - value2.x;
  677. var y = value1.y - value2.y;
  678. var z = value1.z - value2.z;
  679. return (x * x) + (y * y) + (z * z);
  680. };
  681. Vector3.Center = function (value1, value2) {
  682. var center = value1.add(value2);
  683. center.scaleInPlace(0.5);
  684. return center;
  685. };
  686. return Vector3;
  687. })();
  688. BABYLON.Vector3 = Vector3;
  689. var Quaternion = (function () {
  690. function Quaternion(x, y, z, w) {
  691. if (typeof x === "undefined") { x = 0; }
  692. if (typeof y === "undefined") { y = 0; }
  693. if (typeof z === "undefined") { z = 0; }
  694. if (typeof w === "undefined") { w = 1; }
  695. this.x = x;
  696. this.y = y;
  697. this.z = z;
  698. this.w = w;
  699. }
  700. Quaternion.prototype.toString = function () {
  701. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  702. };
  703. Quaternion.prototype.asArray = function () {
  704. return [this.x, this.y, this.z, this.w];
  705. };
  706. Quaternion.prototype.equals = function (otherQuaternion) {
  707. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  708. };
  709. Quaternion.prototype.clone = function () {
  710. return new Quaternion(this.x, this.y, this.z, this.w);
  711. };
  712. Quaternion.prototype.copyFrom = function (other) {
  713. this.x = other.x;
  714. this.y = other.y;
  715. this.z = other.z;
  716. this.w = other.w;
  717. };
  718. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  719. this.x = x;
  720. this.y = y;
  721. this.z = z;
  722. this.w = w;
  723. };
  724. Quaternion.prototype.add = function (other) {
  725. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  726. };
  727. Quaternion.prototype.subtract = function (other) {
  728. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  729. };
  730. Quaternion.prototype.scale = function (value) {
  731. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  732. };
  733. Quaternion.prototype.multiply = function (q1) {
  734. var result = new Quaternion(0, 0, 0, 1.0);
  735. this.multiplyToRef(q1, result);
  736. return result;
  737. };
  738. Quaternion.prototype.multiplyToRef = function (q1, result) {
  739. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  740. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  741. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  742. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  743. };
  744. Quaternion.prototype.length = function () {
  745. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  746. };
  747. Quaternion.prototype.normalize = function () {
  748. var length = 1.0 / this.length();
  749. this.x *= length;
  750. this.y *= length;
  751. this.z *= length;
  752. this.w *= length;
  753. };
  754. Quaternion.prototype.toEulerAngles = function () {
  755. var result = Vector3.Zero();
  756. this.toEulerAnglesToRef(result);
  757. return result;
  758. };
  759. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  760. var qx = this.x;
  761. var qy = this.y;
  762. var qz = this.z;
  763. var qw = this.w;
  764. var sqx = qx * qx;
  765. var sqy = qy * qy;
  766. var sqz = qz * qz;
  767. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  768. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  769. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  770. var gimbaLockTest = qx * qy + qz * qw;
  771. if (gimbaLockTest > 0.499) {
  772. yaw = 2.0 * Math.atan2(qx, qw);
  773. roll = 0;
  774. } else if (gimbaLockTest < -0.499) {
  775. yaw = -2.0 * Math.atan2(qx, qw);
  776. roll = 0;
  777. }
  778. result.x = pitch;
  779. result.y = yaw;
  780. result.z = roll;
  781. };
  782. Quaternion.prototype.toRotationMatrix = function (result) {
  783. var xx = this.x * this.x;
  784. var yy = this.y * this.y;
  785. var zz = this.z * this.z;
  786. var xy = this.x * this.y;
  787. var zw = this.z * this.w;
  788. var zx = this.z * this.x;
  789. var yw = this.y * this.w;
  790. var yz = this.y * this.z;
  791. var xw = this.x * this.w;
  792. result.m[0] = 1.0 - (2.0 * (yy + zz));
  793. result.m[1] = 2.0 * (xy + zw);
  794. result.m[2] = 2.0 * (zx - yw);
  795. result.m[3] = 0;
  796. result.m[4] = 2.0 * (xy - zw);
  797. result.m[5] = 1.0 - (2.0 * (zz + xx));
  798. result.m[6] = 2.0 * (yz + xw);
  799. result.m[7] = 0;
  800. result.m[8] = 2.0 * (zx + yw);
  801. result.m[9] = 2.0 * (yz - xw);
  802. result.m[10] = 1.0 - (2.0 * (yy + xx));
  803. result.m[11] = 0;
  804. result.m[12] = 0;
  805. result.m[13] = 0;
  806. result.m[14] = 0;
  807. result.m[15] = 1.0;
  808. };
  809. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  810. var data = matrix.m;
  811. var m11 = data[0], m12 = data[4], m13 = data[8];
  812. var m21 = data[1], m22 = data[5], m23 = data[9];
  813. var m31 = data[2], m32 = data[6], m33 = data[10];
  814. var trace = m11 + m22 + m33;
  815. var s;
  816. if (trace > 0) {
  817. s = 0.5 / Math.sqrt(trace + 1.0);
  818. this.w = 0.25 / s;
  819. this.x = (m32 - m23) * s;
  820. this.y = (m13 - m31) * s;
  821. this.z = (m21 - m12) * s;
  822. return;
  823. }
  824. if (m11 > m22 && m11 > m33) {
  825. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  826. this.w = (m32 - m23) / s;
  827. this.x = 0.25 * s;
  828. this.y = (m12 + m21) / s;
  829. this.z = (m13 + m31) / s;
  830. return;
  831. }
  832. if (m22 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  834. this.w = (m13 - m31) / s;
  835. this.x = (m12 + m21) / s;
  836. this.y = 0.25 * s;
  837. this.z = (m23 + m32) / s;
  838. return;
  839. }
  840. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  841. this.w = (m21 - m12) / s;
  842. this.x = (m13 + m31) / s;
  843. this.y = (m23 + m32) / s;
  844. this.z = 0.25 * s;
  845. };
  846. Quaternion.Inverse = function (q) {
  847. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  848. };
  849. Quaternion.RotationAxis = function (axis, angle) {
  850. var result = new Quaternion();
  851. var sin = Math.sin(angle / 2);
  852. result.w = Math.cos(angle / 2);
  853. result.x = axis.x * sin;
  854. result.y = axis.y * sin;
  855. result.z = axis.z * sin;
  856. return result;
  857. };
  858. Quaternion.FromArray = function (array, offset) {
  859. if (!offset) {
  860. offset = 0;
  861. }
  862. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  863. };
  864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  865. var result = new Quaternion();
  866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  867. return result;
  868. };
  869. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  870. var halfRoll = roll * 0.5;
  871. var halfPitch = pitch * 0.5;
  872. var halfYaw = yaw * 0.5;
  873. var sinRoll = Math.sin(halfRoll);
  874. var cosRoll = Math.cos(halfRoll);
  875. var sinPitch = Math.sin(halfPitch);
  876. var cosPitch = Math.cos(halfPitch);
  877. var sinYaw = Math.sin(halfYaw);
  878. var cosYaw = Math.cos(halfYaw);
  879. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  880. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  881. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  882. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  883. };
  884. Quaternion.Slerp = function (left, right, amount) {
  885. var num2;
  886. var num3;
  887. var num = amount;
  888. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  889. var flag = false;
  890. if (num4 < 0) {
  891. flag = true;
  892. num4 = -num4;
  893. }
  894. if (num4 > 0.999999) {
  895. num3 = 1 - num;
  896. num2 = flag ? -num : num;
  897. } else {
  898. var num5 = Math.acos(num4);
  899. var num6 = (1.0 / Math.sin(num5));
  900. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  901. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  902. }
  903. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  904. };
  905. return Quaternion;
  906. })();
  907. BABYLON.Quaternion = Quaternion;
  908. var Matrix = (function () {
  909. function Matrix() {
  910. this.m = new Float32Array(16);
  911. }
  912. Matrix.prototype.isIdentity = function () {
  913. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  914. return false;
  915. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  916. return false;
  917. return true;
  918. };
  919. Matrix.prototype.determinant = function () {
  920. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  921. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  922. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  923. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  924. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  925. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  926. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  927. };
  928. Matrix.prototype.toArray = function () {
  929. return this.m;
  930. };
  931. Matrix.prototype.asArray = function () {
  932. return this.toArray();
  933. };
  934. Matrix.prototype.invert = function () {
  935. this.invertToRef(this);
  936. };
  937. Matrix.prototype.invertToRef = function (other) {
  938. var l1 = this.m[0];
  939. var l2 = this.m[1];
  940. var l3 = this.m[2];
  941. var l4 = this.m[3];
  942. var l5 = this.m[4];
  943. var l6 = this.m[5];
  944. var l7 = this.m[6];
  945. var l8 = this.m[7];
  946. var l9 = this.m[8];
  947. var l10 = this.m[9];
  948. var l11 = this.m[10];
  949. var l12 = this.m[11];
  950. var l13 = this.m[12];
  951. var l14 = this.m[13];
  952. var l15 = this.m[14];
  953. var l16 = this.m[15];
  954. var l17 = (l11 * l16) - (l12 * l15);
  955. var l18 = (l10 * l16) - (l12 * l14);
  956. var l19 = (l10 * l15) - (l11 * l14);
  957. var l20 = (l9 * l16) - (l12 * l13);
  958. var l21 = (l9 * l15) - (l11 * l13);
  959. var l22 = (l9 * l14) - (l10 * l13);
  960. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  961. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  962. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  963. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  964. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  965. var l28 = (l7 * l16) - (l8 * l15);
  966. var l29 = (l6 * l16) - (l8 * l14);
  967. var l30 = (l6 * l15) - (l7 * l14);
  968. var l31 = (l5 * l16) - (l8 * l13);
  969. var l32 = (l5 * l15) - (l7 * l13);
  970. var l33 = (l5 * l14) - (l6 * l13);
  971. var l34 = (l7 * l12) - (l8 * l11);
  972. var l35 = (l6 * l12) - (l8 * l10);
  973. var l36 = (l6 * l11) - (l7 * l10);
  974. var l37 = (l5 * l12) - (l8 * l9);
  975. var l38 = (l5 * l11) - (l7 * l9);
  976. var l39 = (l5 * l10) - (l6 * l9);
  977. other.m[0] = l23 * l27;
  978. other.m[4] = l24 * l27;
  979. other.m[8] = l25 * l27;
  980. other.m[12] = l26 * l27;
  981. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  982. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  983. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  984. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  985. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  986. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  987. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  988. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  989. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  990. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  991. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  992. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  993. };
  994. Matrix.prototype.setTranslation = function (vector3) {
  995. this.m[12] = vector3.x;
  996. this.m[13] = vector3.y;
  997. this.m[14] = vector3.z;
  998. };
  999. Matrix.prototype.multiply = function (other) {
  1000. var result = new Matrix();
  1001. this.multiplyToRef(other, result);
  1002. return result;
  1003. };
  1004. Matrix.prototype.copyFrom = function (other) {
  1005. for (var index = 0; index < 16; index++) {
  1006. this.m[index] = other.m[index];
  1007. }
  1008. };
  1009. Matrix.prototype.copyToArray = function (array, offset) {
  1010. if (typeof offset === "undefined") { offset = 0; }
  1011. for (var index = 0; index < 16; index++) {
  1012. array[offset + index] = this.m[index];
  1013. }
  1014. };
  1015. Matrix.prototype.multiplyToRef = function (other, result) {
  1016. this.multiplyToArray(other, result.m, 0);
  1017. };
  1018. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1019. var tm0 = this.m[0];
  1020. var tm1 = this.m[1];
  1021. var tm2 = this.m[2];
  1022. var tm3 = this.m[3];
  1023. var tm4 = this.m[4];
  1024. var tm5 = this.m[5];
  1025. var tm6 = this.m[6];
  1026. var tm7 = this.m[7];
  1027. var tm8 = this.m[8];
  1028. var tm9 = this.m[9];
  1029. var tm10 = this.m[10];
  1030. var tm11 = this.m[11];
  1031. var tm12 = this.m[12];
  1032. var tm13 = this.m[13];
  1033. var tm14 = this.m[14];
  1034. var tm15 = this.m[15];
  1035. var om0 = other.m[0];
  1036. var om1 = other.m[1];
  1037. var om2 = other.m[2];
  1038. var om3 = other.m[3];
  1039. var om4 = other.m[4];
  1040. var om5 = other.m[5];
  1041. var om6 = other.m[6];
  1042. var om7 = other.m[7];
  1043. var om8 = other.m[8];
  1044. var om9 = other.m[9];
  1045. var om10 = other.m[10];
  1046. var om11 = other.m[11];
  1047. var om12 = other.m[12];
  1048. var om13 = other.m[13];
  1049. var om14 = other.m[14];
  1050. var om15 = other.m[15];
  1051. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1052. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1053. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1054. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1055. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1056. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1057. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1058. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1059. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1060. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1061. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1062. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1063. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1064. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1065. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1066. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1067. };
  1068. Matrix.prototype.equals = function (value) {
  1069. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1070. };
  1071. Matrix.prototype.clone = function () {
  1072. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1073. };
  1074. Matrix.FromArray = function (array, offset) {
  1075. var result = new Matrix();
  1076. if (!offset) {
  1077. offset = 0;
  1078. }
  1079. Matrix.FromArrayToRef(array, offset, result);
  1080. return result;
  1081. };
  1082. Matrix.FromArrayToRef = function (array, offset, result) {
  1083. for (var index = 0; index < 16; index++) {
  1084. result.m[index] = array[index + offset];
  1085. }
  1086. };
  1087. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1088. result.m[0] = initialM11;
  1089. result.m[1] = initialM12;
  1090. result.m[2] = initialM13;
  1091. result.m[3] = initialM14;
  1092. result.m[4] = initialM21;
  1093. result.m[5] = initialM22;
  1094. result.m[6] = initialM23;
  1095. result.m[7] = initialM24;
  1096. result.m[8] = initialM31;
  1097. result.m[9] = initialM32;
  1098. result.m[10] = initialM33;
  1099. result.m[11] = initialM34;
  1100. result.m[12] = initialM41;
  1101. result.m[13] = initialM42;
  1102. result.m[14] = initialM43;
  1103. result.m[15] = initialM44;
  1104. };
  1105. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1106. var result = new Matrix();
  1107. result.m[0] = initialM11;
  1108. result.m[1] = initialM12;
  1109. result.m[2] = initialM13;
  1110. result.m[3] = initialM14;
  1111. result.m[4] = initialM21;
  1112. result.m[5] = initialM22;
  1113. result.m[6] = initialM23;
  1114. result.m[7] = initialM24;
  1115. result.m[8] = initialM31;
  1116. result.m[9] = initialM32;
  1117. result.m[10] = initialM33;
  1118. result.m[11] = initialM34;
  1119. result.m[12] = initialM41;
  1120. result.m[13] = initialM42;
  1121. result.m[14] = initialM43;
  1122. result.m[15] = initialM44;
  1123. return result;
  1124. };
  1125. Matrix.Identity = function () {
  1126. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1127. };
  1128. Matrix.IdentityToRef = function (result) {
  1129. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1130. };
  1131. Matrix.Zero = function () {
  1132. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1133. };
  1134. Matrix.RotationX = function (angle) {
  1135. var result = new Matrix();
  1136. Matrix.RotationXToRef(angle, result);
  1137. return result;
  1138. };
  1139. Matrix.RotationXToRef = function (angle, result) {
  1140. var s = Math.sin(angle);
  1141. var c = Math.cos(angle);
  1142. result.m[0] = 1.0;
  1143. result.m[15] = 1.0;
  1144. result.m[5] = c;
  1145. result.m[10] = c;
  1146. result.m[9] = -s;
  1147. result.m[6] = s;
  1148. result.m[1] = 0;
  1149. result.m[2] = 0;
  1150. result.m[3] = 0;
  1151. result.m[4] = 0;
  1152. result.m[7] = 0;
  1153. result.m[8] = 0;
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. };
  1159. Matrix.RotationY = function (angle) {
  1160. var result = new Matrix();
  1161. Matrix.RotationYToRef(angle, result);
  1162. return result;
  1163. };
  1164. Matrix.RotationYToRef = function (angle, result) {
  1165. var s = Math.sin(angle);
  1166. var c = Math.cos(angle);
  1167. result.m[5] = 1.0;
  1168. result.m[15] = 1.0;
  1169. result.m[0] = c;
  1170. result.m[2] = -s;
  1171. result.m[8] = s;
  1172. result.m[10] = c;
  1173. result.m[1] = 0;
  1174. result.m[3] = 0;
  1175. result.m[4] = 0;
  1176. result.m[6] = 0;
  1177. result.m[7] = 0;
  1178. result.m[9] = 0;
  1179. result.m[11] = 0;
  1180. result.m[12] = 0;
  1181. result.m[13] = 0;
  1182. result.m[14] = 0;
  1183. };
  1184. Matrix.RotationZ = function (angle) {
  1185. var result = new Matrix();
  1186. Matrix.RotationZToRef(angle, result);
  1187. return result;
  1188. };
  1189. Matrix.RotationZToRef = function (angle, result) {
  1190. var s = Math.sin(angle);
  1191. var c = Math.cos(angle);
  1192. result.m[10] = 1.0;
  1193. result.m[15] = 1.0;
  1194. result.m[0] = c;
  1195. result.m[1] = s;
  1196. result.m[4] = -s;
  1197. result.m[5] = c;
  1198. result.m[2] = 0;
  1199. result.m[3] = 0;
  1200. result.m[6] = 0;
  1201. result.m[7] = 0;
  1202. result.m[8] = 0;
  1203. result.m[9] = 0;
  1204. result.m[11] = 0;
  1205. result.m[12] = 0;
  1206. result.m[13] = 0;
  1207. result.m[14] = 0;
  1208. };
  1209. Matrix.RotationAxis = function (axis, angle) {
  1210. var s = Math.sin(-angle);
  1211. var c = Math.cos(-angle);
  1212. var c1 = 1 - c;
  1213. axis.normalize();
  1214. var result = Matrix.Zero();
  1215. result.m[0] = (axis.x * axis.x) * c1 + c;
  1216. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1217. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1218. result.m[3] = 0.0;
  1219. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1220. result.m[5] = (axis.y * axis.y) * c1 + c;
  1221. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1222. result.m[7] = 0.0;
  1223. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1224. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1225. result.m[10] = (axis.z * axis.z) * c1 + c;
  1226. result.m[11] = 0.0;
  1227. result.m[15] = 1.0;
  1228. return result;
  1229. };
  1230. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1231. var result = new Matrix();
  1232. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1233. return result;
  1234. };
  1235. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1236. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1237. this._tempQuaternion.toRotationMatrix(result);
  1238. };
  1239. Matrix.Scaling = function (x, y, z) {
  1240. var result = Matrix.Zero();
  1241. Matrix.ScalingToRef(x, y, z, result);
  1242. return result;
  1243. };
  1244. Matrix.ScalingToRef = function (x, y, z, result) {
  1245. result.m[0] = x;
  1246. result.m[1] = 0;
  1247. result.m[2] = 0;
  1248. result.m[3] = 0;
  1249. result.m[4] = 0;
  1250. result.m[5] = y;
  1251. result.m[6] = 0;
  1252. result.m[7] = 0;
  1253. result.m[8] = 0;
  1254. result.m[9] = 0;
  1255. result.m[10] = z;
  1256. result.m[11] = 0;
  1257. result.m[12] = 0;
  1258. result.m[13] = 0;
  1259. result.m[14] = 0;
  1260. result.m[15] = 1.0;
  1261. };
  1262. Matrix.Translation = function (x, y, z) {
  1263. var result = Matrix.Identity();
  1264. Matrix.TranslationToRef(x, y, z, result);
  1265. return result;
  1266. };
  1267. Matrix.TranslationToRef = function (x, y, z, result) {
  1268. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1269. };
  1270. Matrix.LookAtLH = function (eye, target, up) {
  1271. var result = Matrix.Zero();
  1272. Matrix.LookAtLHToRef(eye, target, up, result);
  1273. return result;
  1274. };
  1275. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1276. target.subtractToRef(eye, this._zAxis);
  1277. this._zAxis.normalize();
  1278. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1279. this._xAxis.normalize();
  1280. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1281. this._yAxis.normalize();
  1282. var ex = -Vector3.Dot(this._xAxis, eye);
  1283. var ey = -Vector3.Dot(this._yAxis, eye);
  1284. var ez = -Vector3.Dot(this._zAxis, eye);
  1285. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1286. };
  1287. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1288. var hw = 2.0 / width;
  1289. var hh = 2.0 / height;
  1290. var id = 1.0 / (zfar - znear);
  1291. var nid = znear / (znear - zfar);
  1292. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1293. };
  1294. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1295. var matrix = Matrix.Zero();
  1296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1297. return matrix;
  1298. };
  1299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1300. result.m[0] = 2.0 / (right - left);
  1301. result.m[1] = result.m[2] = result.m[3] = 0;
  1302. result.m[5] = 2.0 / (top - bottom);
  1303. result.m[4] = result.m[6] = result.m[7] = 0;
  1304. result.m[10] = -1.0 / (znear - zfar);
  1305. result.m[8] = result.m[9] = result.m[11] = 0;
  1306. result.m[12] = (left + right) / (left - right);
  1307. result.m[13] = (top + bottom) / (bottom - top);
  1308. result.m[14] = znear / (znear - zfar);
  1309. result.m[15] = 1.0;
  1310. };
  1311. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1312. var matrix = Matrix.Zero();
  1313. matrix.m[0] = (2.0 * znear) / width;
  1314. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1315. matrix.m[5] = (2.0 * znear) / height;
  1316. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1317. matrix.m[10] = -zfar / (znear - zfar);
  1318. matrix.m[8] = matrix.m[9] = 0.0;
  1319. matrix.m[11] = 1.0;
  1320. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1321. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1322. return matrix;
  1323. };
  1324. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1325. var matrix = Matrix.Zero();
  1326. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1327. return matrix;
  1328. };
  1329. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1330. var tan = 1.0 / (Math.tan(fov * 0.5));
  1331. result.m[0] = tan / aspect;
  1332. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1333. result.m[5] = tan;
  1334. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1335. result.m[8] = result.m[9] = 0.0;
  1336. result.m[10] = -zfar / (znear - zfar);
  1337. result.m[11] = 1.0;
  1338. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1339. result.m[14] = (znear * zfar) / (znear - zfar);
  1340. };
  1341. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1342. var cw = viewport.width;
  1343. var ch = viewport.height;
  1344. var cx = viewport.x;
  1345. var cy = viewport.y;
  1346. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1347. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1348. };
  1349. Matrix.Transpose = function (matrix) {
  1350. var result = new Matrix();
  1351. result.m[0] = matrix.m[0];
  1352. result.m[1] = matrix.m[4];
  1353. result.m[2] = matrix.m[8];
  1354. result.m[3] = matrix.m[12];
  1355. result.m[4] = matrix.m[1];
  1356. result.m[5] = matrix.m[5];
  1357. result.m[6] = matrix.m[9];
  1358. result.m[7] = matrix.m[13];
  1359. result.m[8] = matrix.m[2];
  1360. result.m[9] = matrix.m[6];
  1361. result.m[10] = matrix.m[10];
  1362. result.m[11] = matrix.m[14];
  1363. result.m[12] = matrix.m[3];
  1364. result.m[13] = matrix.m[7];
  1365. result.m[14] = matrix.m[11];
  1366. result.m[15] = matrix.m[15];
  1367. return result;
  1368. };
  1369. Matrix.Reflection = function (plane) {
  1370. var matrix = new Matrix();
  1371. Matrix.ReflectionToRef(plane, matrix);
  1372. return matrix;
  1373. };
  1374. Matrix.ReflectionToRef = function (plane, result) {
  1375. plane.normalize();
  1376. var x = plane.normal.x;
  1377. var y = plane.normal.y;
  1378. var z = plane.normal.z;
  1379. var temp = -2 * x;
  1380. var temp2 = -2 * y;
  1381. var temp3 = -2 * z;
  1382. result.m[0] = (temp * x) + 1;
  1383. result.m[1] = temp2 * x;
  1384. result.m[2] = temp3 * x;
  1385. result.m[3] = 0.0;
  1386. result.m[4] = temp * y;
  1387. result.m[5] = (temp2 * y) + 1;
  1388. result.m[6] = temp3 * y;
  1389. result.m[7] = 0.0;
  1390. result.m[8] = temp * z;
  1391. result.m[9] = temp2 * z;
  1392. result.m[10] = (temp3 * z) + 1;
  1393. result.m[11] = 0.0;
  1394. result.m[12] = temp * plane.d;
  1395. result.m[13] = temp2 * plane.d;
  1396. result.m[14] = temp3 * plane.d;
  1397. result.m[15] = 1.0;
  1398. };
  1399. Matrix._tempQuaternion = new Quaternion();
  1400. Matrix._xAxis = Vector3.Zero();
  1401. Matrix._yAxis = Vector3.Zero();
  1402. Matrix._zAxis = Vector3.Zero();
  1403. return Matrix;
  1404. })();
  1405. BABYLON.Matrix = Matrix;
  1406. var Plane = (function () {
  1407. function Plane(a, b, c, d) {
  1408. this.normal = new Vector3(a, b, c);
  1409. this.d = d;
  1410. }
  1411. Plane.prototype.asArray = function () {
  1412. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1413. };
  1414. Plane.prototype.clone = function () {
  1415. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1416. };
  1417. Plane.prototype.normalize = function () {
  1418. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1419. var magnitude = 0;
  1420. if (norm != 0) {
  1421. magnitude = 1.0 / norm;
  1422. }
  1423. this.normal.x *= magnitude;
  1424. this.normal.y *= magnitude;
  1425. this.normal.z *= magnitude;
  1426. this.d *= magnitude;
  1427. };
  1428. Plane.prototype.transform = function (transformation) {
  1429. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1430. var x = this.normal.x;
  1431. var y = this.normal.y;
  1432. var z = this.normal.z;
  1433. var d = this.d;
  1434. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1435. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1436. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1437. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1438. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1439. };
  1440. Plane.prototype.dotCoordinate = function (point) {
  1441. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1442. };
  1443. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1444. var x1 = point2.x - point1.x;
  1445. var y1 = point2.y - point1.y;
  1446. var z1 = point2.z - point1.z;
  1447. var x2 = point3.x - point1.x;
  1448. var y2 = point3.y - point1.y;
  1449. var z2 = point3.z - point1.z;
  1450. var yz = (y1 * z2) - (z1 * y2);
  1451. var xz = (z1 * x2) - (x1 * z2);
  1452. var xy = (x1 * y2) - (y1 * x2);
  1453. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1454. var invPyth;
  1455. if (pyth != 0) {
  1456. invPyth = 1.0 / pyth;
  1457. } else {
  1458. invPyth = 0;
  1459. }
  1460. this.normal.x = yz * invPyth;
  1461. this.normal.y = xz * invPyth;
  1462. this.normal.z = xy * invPyth;
  1463. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1464. };
  1465. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1466. var dot = Vector3.Dot(this.normal, direction);
  1467. return (dot <= epsilon);
  1468. };
  1469. Plane.prototype.signedDistanceTo = function (point) {
  1470. return Vector3.Dot(point, this.normal) + this.d;
  1471. };
  1472. Plane.FromArray = function (array) {
  1473. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1474. };
  1475. Plane.FromPoints = function (point1, point2, point3) {
  1476. var result = new BABYLON.Plane(0, 0, 0, 0);
  1477. result.copyFromPoints(point1, point2, point3);
  1478. return result;
  1479. };
  1480. Plane.FromPositionAndNormal = function (origin, normal) {
  1481. var result = new BABYLON.Plane(0, 0, 0, 0);
  1482. normal.normalize();
  1483. result.normal = normal;
  1484. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1485. return result;
  1486. };
  1487. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1488. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1489. return Vector3.Dot(point, normal) + d;
  1490. };
  1491. return Plane;
  1492. })();
  1493. BABYLON.Plane = Plane;
  1494. var Viewport = (function () {
  1495. function Viewport(x, y, width, height) {
  1496. this.x = x;
  1497. this.y = y;
  1498. this.width = width;
  1499. this.height = height;
  1500. }
  1501. Viewport.prototype.toGlobal = function (engine) {
  1502. var width = engine.getRenderWidth();
  1503. var height = engine.getRenderHeight();
  1504. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1505. };
  1506. return Viewport;
  1507. })();
  1508. BABYLON.Viewport = Viewport;
  1509. var Frustum = (function () {
  1510. function Frustum() {
  1511. }
  1512. Frustum.GetPlanes = function (transform) {
  1513. var frustumPlanes = [];
  1514. for (var index = 0; index < 6; index++) {
  1515. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1516. }
  1517. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1518. return frustumPlanes;
  1519. };
  1520. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1521. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1522. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1523. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1524. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1525. frustumPlanes[0].normalize();
  1526. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1527. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1528. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1529. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1530. frustumPlanes[1].normalize();
  1531. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1532. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1533. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1534. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1535. frustumPlanes[2].normalize();
  1536. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1537. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1538. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1539. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1540. frustumPlanes[3].normalize();
  1541. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1542. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1543. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1544. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1545. frustumPlanes[4].normalize();
  1546. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1547. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1548. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1549. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1550. frustumPlanes[5].normalize();
  1551. };
  1552. return Frustum;
  1553. })();
  1554. BABYLON.Frustum = Frustum;
  1555. var Ray = (function () {
  1556. function Ray(origin, direction) {
  1557. this.origin = origin;
  1558. this.direction = direction;
  1559. }
  1560. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1561. var d = 0.0;
  1562. var maxValue = Number.MAX_VALUE;
  1563. if (Math.abs(this.direction.x) < 0.0000001) {
  1564. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1565. return false;
  1566. }
  1567. } else {
  1568. var inv = 1.0 / this.direction.x;
  1569. var min = (minimum.x - this.origin.x) * inv;
  1570. var max = (maximum.x - this.origin.x) * inv;
  1571. if (min > max) {
  1572. var temp = min;
  1573. min = max;
  1574. max = temp;
  1575. }
  1576. d = Math.max(min, d);
  1577. maxValue = Math.min(max, maxValue);
  1578. if (d > maxValue) {
  1579. return false;
  1580. }
  1581. }
  1582. if (Math.abs(this.direction.y) < 0.0000001) {
  1583. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1584. return false;
  1585. }
  1586. } else {
  1587. inv = 1.0 / this.direction.y;
  1588. min = (minimum.y - this.origin.y) * inv;
  1589. max = (maximum.y - this.origin.y) * inv;
  1590. if (min > max) {
  1591. temp = min;
  1592. min = max;
  1593. max = temp;
  1594. }
  1595. d = Math.max(min, d);
  1596. maxValue = Math.min(max, maxValue);
  1597. if (d > maxValue) {
  1598. return false;
  1599. }
  1600. }
  1601. if (Math.abs(this.direction.z) < 0.0000001) {
  1602. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1603. return false;
  1604. }
  1605. } else {
  1606. inv = 1.0 / this.direction.z;
  1607. min = (minimum.z - this.origin.z) * inv;
  1608. max = (maximum.z - this.origin.z) * inv;
  1609. if (min > max) {
  1610. temp = min;
  1611. min = max;
  1612. max = temp;
  1613. }
  1614. d = Math.max(min, d);
  1615. maxValue = Math.min(max, maxValue);
  1616. if (d > maxValue) {
  1617. return false;
  1618. }
  1619. }
  1620. return true;
  1621. };
  1622. Ray.prototype.intersectsBox = function (box) {
  1623. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1624. };
  1625. Ray.prototype.intersectsSphere = function (sphere) {
  1626. var x = sphere.center.x - this.origin.x;
  1627. var y = sphere.center.y - this.origin.y;
  1628. var z = sphere.center.z - this.origin.z;
  1629. var pyth = (x * x) + (y * y) + (z * z);
  1630. var rr = sphere.radius * sphere.radius;
  1631. if (pyth <= rr) {
  1632. return true;
  1633. }
  1634. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1635. if (dot < 0.0) {
  1636. return false;
  1637. }
  1638. var temp = pyth - (dot * dot);
  1639. return temp <= rr;
  1640. };
  1641. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1642. if (!this._edge1) {
  1643. this._edge1 = BABYLON.Vector3.Zero();
  1644. this._edge2 = BABYLON.Vector3.Zero();
  1645. this._pvec = BABYLON.Vector3.Zero();
  1646. this._tvec = BABYLON.Vector3.Zero();
  1647. this._qvec = BABYLON.Vector3.Zero();
  1648. }
  1649. vertex1.subtractToRef(vertex0, this._edge1);
  1650. vertex2.subtractToRef(vertex0, this._edge2);
  1651. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1652. var det = Vector3.Dot(this._edge1, this._pvec);
  1653. if (det === 0) {
  1654. return null;
  1655. }
  1656. var invdet = 1 / det;
  1657. this.origin.subtractToRef(vertex0, this._tvec);
  1658. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1659. if (bu < 0 || bu > 1.0) {
  1660. return null;
  1661. }
  1662. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1663. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1664. if (bv < 0 || bu + bv > 1.0) {
  1665. return null;
  1666. }
  1667. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1668. };
  1669. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1670. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1671. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1672. var direction = end.subtract(start);
  1673. direction.normalize();
  1674. return new Ray(start, direction);
  1675. };
  1676. Ray.Transform = function (ray, matrix) {
  1677. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1678. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1679. return new Ray(newOrigin, newDirection);
  1680. };
  1681. return Ray;
  1682. })();
  1683. BABYLON.Ray = Ray;
  1684. (function (Space) {
  1685. Space[Space["LOCAL"] = 0] = "LOCAL";
  1686. Space[Space["WORLD"] = 1] = "WORLD";
  1687. })(BABYLON.Space || (BABYLON.Space = {}));
  1688. var Space = BABYLON.Space;
  1689. var Axis = (function () {
  1690. function Axis() {
  1691. }
  1692. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1693. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1694. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1695. return Axis;
  1696. })();
  1697. BABYLON.Axis = Axis;
  1698. ;
  1699. })(BABYLON || (BABYLON = {}));
  1700. var BABYLON;
  1701. (function (BABYLON) {
  1702. var screenshotCanvas;
  1703. var fpsRange = 60;
  1704. var previousFramesDuration = [];
  1705. var fps = 60;
  1706. var deltaTime = 0;
  1707. var cloneValue = function (source, destinationObject) {
  1708. if (!source)
  1709. return null;
  1710. if (source instanceof BABYLON.Mesh) {
  1711. return null;
  1712. }
  1713. if (source instanceof BABYLON.SubMesh) {
  1714. return source.clone(destinationObject);
  1715. } else if (source.clone) {
  1716. return source.clone();
  1717. }
  1718. return null;
  1719. };
  1720. var Tools = (function () {
  1721. function Tools() {
  1722. }
  1723. Tools.GetFilename = function (path) {
  1724. var index = path.lastIndexOf("/");
  1725. if (index < 0)
  1726. return path;
  1727. return path.substring(index + 1);
  1728. };
  1729. Tools.GetDOMTextContent = function (element) {
  1730. var result = "";
  1731. var child = element.firstChild;
  1732. while (child) {
  1733. if (child.nodeType == 3) {
  1734. result += child.textContent;
  1735. }
  1736. child = child.nextSibling;
  1737. }
  1738. return result;
  1739. };
  1740. Tools.ToDegrees = function (angle) {
  1741. return angle * 180 / Math.PI;
  1742. };
  1743. Tools.ToRadians = function (angle) {
  1744. return angle * Math.PI / 180;
  1745. };
  1746. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1747. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1748. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1749. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1750. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1751. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1752. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1753. }
  1754. return {
  1755. minimum: minimum,
  1756. maximum: maximum
  1757. };
  1758. };
  1759. Tools.ExtractMinAndMax = function (positions, start, count) {
  1760. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1761. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1762. for (var index = start; index < start + count; index++) {
  1763. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1764. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1765. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1766. }
  1767. return {
  1768. minimum: minimum,
  1769. maximum: maximum
  1770. };
  1771. };
  1772. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1773. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1774. return undefined;
  1775. return Array.isArray(obj) ? obj : [obj];
  1776. };
  1777. Tools.GetPointerPrefix = function () {
  1778. var eventPrefix = "pointer";
  1779. if (!navigator.pointerEnabled) {
  1780. eventPrefix = "mouse";
  1781. }
  1782. return eventPrefix;
  1783. };
  1784. Tools.QueueNewFrame = function (func) {
  1785. if (window.requestAnimationFrame)
  1786. window.requestAnimationFrame(func);
  1787. else if (window.msRequestAnimationFrame)
  1788. window.msRequestAnimationFrame(func);
  1789. else if (window.webkitRequestAnimationFrame)
  1790. window.webkitRequestAnimationFrame(func);
  1791. else if (window.mozRequestAnimationFrame)
  1792. window.mozRequestAnimationFrame(func);
  1793. else if (window.oRequestAnimationFrame)
  1794. window.oRequestAnimationFrame(func);
  1795. else {
  1796. window.setTimeout(func, 16);
  1797. }
  1798. };
  1799. Tools.RequestFullscreen = function (element) {
  1800. if (element.requestFullscreen)
  1801. element.requestFullscreen();
  1802. else if (element.msRequestFullscreen)
  1803. element.msRequestFullscreen();
  1804. else if (element.webkitRequestFullscreen)
  1805. element.webkitRequestFullscreen();
  1806. else if (element.mozRequestFullScreen)
  1807. element.mozRequestFullScreen();
  1808. };
  1809. Tools.ExitFullscreen = function () {
  1810. if (document.exitFullscreen) {
  1811. document.exitFullscreen();
  1812. } else if (document.mozCancelFullScreen) {
  1813. document.mozCancelFullScreen();
  1814. } else if (document.webkitCancelFullScreen) {
  1815. document.webkitCancelFullScreen();
  1816. } else if (document.msCancelFullScreen) {
  1817. document.msCancelFullScreen();
  1818. }
  1819. };
  1820. Tools.CleanUrl = function (url) {
  1821. url = url.replace(/#/mg, "%23");
  1822. return url;
  1823. };
  1824. Tools.LoadImage = function (url, onload, onerror, database) {
  1825. url = Tools.CleanUrl(url);
  1826. var img = new Image();
  1827. img.crossOrigin = 'anonymous';
  1828. img.onload = function () {
  1829. onload(img);
  1830. };
  1831. img.onerror = function (err) {
  1832. onerror(img, err);
  1833. };
  1834. var noIndexedDB = function () {
  1835. img.src = url;
  1836. };
  1837. var loadFromIndexedDB = function () {
  1838. database.loadImageFromDB(url, img);
  1839. };
  1840. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1841. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1842. } else {
  1843. if (url.indexOf("file:") === -1) {
  1844. noIndexedDB();
  1845. } else {
  1846. try {
  1847. var textureName = url.substring(5);
  1848. var blobURL;
  1849. try {
  1850. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1851. } catch (ex) {
  1852. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1853. }
  1854. img.src = blobURL;
  1855. } catch (e) {
  1856. Tools.Log("Error while trying to load texture: " + textureName);
  1857. img.src = null;
  1858. }
  1859. }
  1860. }
  1861. return img;
  1862. };
  1863. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1864. url = Tools.CleanUrl(url);
  1865. var noIndexedDB = function () {
  1866. var request = new XMLHttpRequest();
  1867. var loadUrl = Tools.BaseUrl + url;
  1868. request.open('GET', loadUrl, true);
  1869. if (useArrayBuffer) {
  1870. request.responseType = "arraybuffer";
  1871. }
  1872. request.onprogress = progressCallBack;
  1873. request.onreadystatechange = function () {
  1874. if (request.readyState == 4) {
  1875. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1876. callback(!useArrayBuffer ? request.responseText : request.response);
  1877. } else {
  1878. if (onError) {
  1879. onError();
  1880. } else {
  1881. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1882. }
  1883. }
  1884. }
  1885. };
  1886. request.send(null);
  1887. };
  1888. var loadFromIndexedDB = function () {
  1889. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1890. };
  1891. if (url.indexOf("file:") !== -1) {
  1892. var fileName = url.substring(5);
  1893. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1894. } else {
  1895. if (database && database.enableSceneOffline) {
  1896. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1897. } else {
  1898. noIndexedDB();
  1899. }
  1900. }
  1901. };
  1902. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1903. var reader = new FileReader();
  1904. reader.onload = function (e) {
  1905. callback(e.target.result);
  1906. };
  1907. reader.onprogress = progressCallBack;
  1908. if (!useArrayBuffer) {
  1909. reader.readAsText(fileToLoad);
  1910. } else {
  1911. reader.readAsArrayBuffer(fileToLoad);
  1912. }
  1913. };
  1914. Tools.CheckExtends = function (v, min, max) {
  1915. if (v.x < min.x)
  1916. min.x = v.x;
  1917. if (v.y < min.y)
  1918. min.y = v.y;
  1919. if (v.z < min.z)
  1920. min.z = v.z;
  1921. if (v.x > max.x)
  1922. max.x = v.x;
  1923. if (v.y > max.y)
  1924. max.y = v.y;
  1925. if (v.z > max.z)
  1926. max.z = v.z;
  1927. };
  1928. Tools.WithinEpsilon = function (a, b) {
  1929. var num = a - b;
  1930. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1931. };
  1932. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1933. for (var prop in source) {
  1934. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1935. continue;
  1936. }
  1937. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1938. continue;
  1939. }
  1940. var sourceValue = source[prop];
  1941. var typeOfSourceValue = typeof sourceValue;
  1942. if (typeOfSourceValue == "function") {
  1943. continue;
  1944. }
  1945. if (typeOfSourceValue == "object") {
  1946. if (sourceValue instanceof Array) {
  1947. destination[prop] = [];
  1948. if (sourceValue.length > 0) {
  1949. if (typeof sourceValue[0] == "object") {
  1950. for (var index = 0; index < sourceValue.length; index++) {
  1951. var clonedValue = cloneValue(sourceValue[index], destination);
  1952. if (destination[prop].indexOf(clonedValue) === -1) {
  1953. destination[prop].push(clonedValue);
  1954. }
  1955. }
  1956. } else {
  1957. destination[prop] = sourceValue.slice(0);
  1958. }
  1959. }
  1960. } else {
  1961. destination[prop] = cloneValue(sourceValue, destination);
  1962. }
  1963. } else {
  1964. destination[prop] = sourceValue;
  1965. }
  1966. }
  1967. };
  1968. Tools.IsEmpty = function (obj) {
  1969. for (var i in obj) {
  1970. return false;
  1971. }
  1972. return true;
  1973. };
  1974. Tools.RegisterTopRootEvents = function (events) {
  1975. for (var index = 0; index < events.length; index++) {
  1976. var event = events[index];
  1977. window.addEventListener(event.name, event.handler, false);
  1978. try {
  1979. if (window.parent) {
  1980. window.parent.addEventListener(event.name, event.handler, false);
  1981. }
  1982. } catch (e) {
  1983. }
  1984. }
  1985. };
  1986. Tools.UnregisterTopRootEvents = function (events) {
  1987. for (var index = 0; index < events.length; index++) {
  1988. var event = events[index];
  1989. window.removeEventListener(event.name, event.handler);
  1990. try {
  1991. if (window.parent) {
  1992. window.parent.removeEventListener(event.name, event.handler);
  1993. }
  1994. } catch (e) {
  1995. }
  1996. }
  1997. };
  1998. Tools.GetFps = function () {
  1999. return fps;
  2000. };
  2001. Tools.GetDeltaTime = function () {
  2002. return deltaTime;
  2003. };
  2004. Tools._MeasureFps = function () {
  2005. previousFramesDuration.push((new Date).getTime());
  2006. var length = previousFramesDuration.length;
  2007. if (length >= 2) {
  2008. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2009. }
  2010. if (length >= fpsRange) {
  2011. if (length > fpsRange) {
  2012. previousFramesDuration.splice(0, 1);
  2013. length = previousFramesDuration.length;
  2014. }
  2015. var sum = 0;
  2016. for (var id = 0; id < length - 1; id++) {
  2017. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2018. }
  2019. fps = 1000.0 / (sum / (length - 1));
  2020. }
  2021. };
  2022. Tools.CreateScreenshot = function (engine, camera, size) {
  2023. var width;
  2024. var height;
  2025. var scene = camera.getScene();
  2026. var previousCamera = null;
  2027. if (scene.activeCamera !== camera) {
  2028. previousCamera = scene.activeCamera;
  2029. scene.activeCamera = camera;
  2030. }
  2031. if (size.precision) {
  2032. width = Math.round(engine.getRenderWidth() * size.precision);
  2033. height = Math.round(width / engine.getAspectRatio(camera));
  2034. size = { width: width, height: height };
  2035. } else if (size.width && size.height) {
  2036. width = size.width;
  2037. height = size.height;
  2038. } else if (size.width && !size.height) {
  2039. width = size.width;
  2040. height = Math.round(width / engine.getAspectRatio(camera));
  2041. size = { width: width, height: height };
  2042. } else if (size.height && !size.width) {
  2043. height = size.height;
  2044. width = Math.round(height * engine.getAspectRatio(camera));
  2045. size = { width: width, height: height };
  2046. } else if (!isNaN(size)) {
  2047. height = size;
  2048. width = size;
  2049. } else {
  2050. Tools.Error("Invalid 'size' parameter !");
  2051. return;
  2052. }
  2053. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2054. texture.renderList = engine.scenes[0].meshes;
  2055. texture.onAfterRender = function () {
  2056. var numberOfChannelsByLine = width * 4;
  2057. var halfHeight = height / 2;
  2058. var data = engine.readPixels(0, 0, width, height);
  2059. for (var i = 0; i < halfHeight; i++) {
  2060. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2061. var currentCell = j + i * numberOfChannelsByLine;
  2062. var targetLine = height - i - 1;
  2063. var targetCell = j + targetLine * numberOfChannelsByLine;
  2064. var temp = data[currentCell];
  2065. data[currentCell] = data[targetCell];
  2066. data[targetCell] = temp;
  2067. }
  2068. }
  2069. if (!screenshotCanvas) {
  2070. screenshotCanvas = document.createElement('canvas');
  2071. }
  2072. screenshotCanvas.width = width;
  2073. screenshotCanvas.height = height;
  2074. var context = screenshotCanvas.getContext('2d');
  2075. var imageData = context.createImageData(width, height);
  2076. imageData.data.set(data);
  2077. context.putImageData(imageData, 0, 0);
  2078. var base64Image = screenshotCanvas.toDataURL();
  2079. if (("download" in document.createElement("a"))) {
  2080. var a = window.document.createElement("a");
  2081. a.href = base64Image;
  2082. var date = new Date();
  2083. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2084. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2085. window.document.body.appendChild(a);
  2086. a.addEventListener("click", function () {
  2087. a.parentElement.removeChild(a);
  2088. });
  2089. a.click();
  2090. } else {
  2091. var newWindow = window.open("");
  2092. var img = newWindow.document.createElement("img");
  2093. img.src = base64Image;
  2094. newWindow.document.body.appendChild(img);
  2095. }
  2096. };
  2097. texture.render(true);
  2098. texture.dispose();
  2099. if (previousCamera) {
  2100. scene.activeCamera = previousCamera;
  2101. }
  2102. };
  2103. Tools.ValidateXHRData = function (xhr, dataType) {
  2104. if (typeof dataType === "undefined") { dataType = 7; }
  2105. try {
  2106. if (dataType & 1) {
  2107. if (xhr.responseText && xhr.responseText.length > 0) {
  2108. return true;
  2109. } else if (dataType === 1) {
  2110. return false;
  2111. }
  2112. }
  2113. if (dataType & 2) {
  2114. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2115. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2116. return true;
  2117. } else if (dataType === 2) {
  2118. return false;
  2119. }
  2120. }
  2121. if (dataType & 4) {
  2122. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2123. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2124. return true;
  2125. } else {
  2126. return false;
  2127. }
  2128. }
  2129. } catch (e) {
  2130. }
  2131. return false;
  2132. };
  2133. Object.defineProperty(Tools, "NoneLogLevel", {
  2134. get: function () {
  2135. return Tools._NoneLogLevel;
  2136. },
  2137. enumerable: true,
  2138. configurable: true
  2139. });
  2140. Object.defineProperty(Tools, "MessageLogLevel", {
  2141. get: function () {
  2142. return Tools._MessageLogLevel;
  2143. },
  2144. enumerable: true,
  2145. configurable: true
  2146. });
  2147. Object.defineProperty(Tools, "WarningLogLevel", {
  2148. get: function () {
  2149. return Tools._WarningLogLevel;
  2150. },
  2151. enumerable: true,
  2152. configurable: true
  2153. });
  2154. Object.defineProperty(Tools, "ErrorLogLevel", {
  2155. get: function () {
  2156. return Tools._ErrorLogLevel;
  2157. },
  2158. enumerable: true,
  2159. configurable: true
  2160. });
  2161. Object.defineProperty(Tools, "AllLogLevel", {
  2162. get: function () {
  2163. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2164. },
  2165. enumerable: true,
  2166. configurable: true
  2167. });
  2168. Tools._FormatMessage = function (message) {
  2169. var padStr = function (i) {
  2170. return (i < 10) ? "0" + i : "" + i;
  2171. };
  2172. var date = new Date();
  2173. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2174. };
  2175. Tools._LogDisabled = function (message) {
  2176. };
  2177. Tools._LogEnabled = function (message) {
  2178. console.log(Tools._FormatMessage(message));
  2179. };
  2180. Tools._WarnDisabled = function (message) {
  2181. };
  2182. Tools._WarnEnabled = function (message) {
  2183. console.warn(Tools._FormatMessage(message));
  2184. };
  2185. Tools._ErrorDisabled = function (message) {
  2186. };
  2187. Tools._ErrorEnabled = function (message) {
  2188. console.error(Tools._FormatMessage(message));
  2189. };
  2190. Object.defineProperty(Tools, "LogLevels", {
  2191. set: function (level) {
  2192. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2193. Tools.Log = Tools._LogEnabled;
  2194. } else {
  2195. Tools.Log = Tools._LogDisabled;
  2196. }
  2197. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2198. Tools.Warn = Tools._WarnEnabled;
  2199. } else {
  2200. Tools.Warn = Tools._WarnDisabled;
  2201. }
  2202. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2203. Tools.Error = Tools._ErrorEnabled;
  2204. } else {
  2205. Tools.Error = Tools._ErrorDisabled;
  2206. }
  2207. },
  2208. enumerable: true,
  2209. configurable: true
  2210. });
  2211. Tools.BaseUrl = "";
  2212. Tools.GetExponantOfTwo = function (value, max) {
  2213. var count = 1;
  2214. do {
  2215. count *= 2;
  2216. } while(count < value);
  2217. if (count > max)
  2218. count = max;
  2219. return count;
  2220. };
  2221. Tools._NoneLogLevel = 0;
  2222. Tools._MessageLogLevel = 1;
  2223. Tools._WarningLogLevel = 2;
  2224. Tools._ErrorLogLevel = 4;
  2225. Tools.Log = Tools._LogEnabled;
  2226. Tools.Warn = Tools._WarnEnabled;
  2227. Tools.Error = Tools._ErrorEnabled;
  2228. return Tools;
  2229. })();
  2230. BABYLON.Tools = Tools;
  2231. })(BABYLON || (BABYLON = {}));
  2232. var BABYLON;
  2233. (function (BABYLON) {
  2234. var _DepthCullingState = (function () {
  2235. function _DepthCullingState() {
  2236. this._isDepthTestDirty = false;
  2237. this._isDepthMaskDirty = false;
  2238. this._isDepthFuncDirty = false;
  2239. this._isCullFaceDirty = false;
  2240. this._isCullDirty = false;
  2241. }
  2242. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2243. get: function () {
  2244. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2245. },
  2246. enumerable: true,
  2247. configurable: true
  2248. });
  2249. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2250. get: function () {
  2251. return this._cullFace;
  2252. },
  2253. set: function (value) {
  2254. if (this._cullFace === value) {
  2255. return;
  2256. }
  2257. this._cullFace = value;
  2258. this._isCullFaceDirty = true;
  2259. },
  2260. enumerable: true,
  2261. configurable: true
  2262. });
  2263. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2264. get: function () {
  2265. return this._cull;
  2266. },
  2267. set: function (value) {
  2268. if (this._cull === value) {
  2269. return;
  2270. }
  2271. this._cull = value;
  2272. this._isCullDirty = true;
  2273. },
  2274. enumerable: true,
  2275. configurable: true
  2276. });
  2277. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2278. get: function () {
  2279. return this._depthFunc;
  2280. },
  2281. set: function (value) {
  2282. if (this._depthFunc === value) {
  2283. return;
  2284. }
  2285. this._depthFunc = value;
  2286. this._isDepthFuncDirty = true;
  2287. },
  2288. enumerable: true,
  2289. configurable: true
  2290. });
  2291. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2292. get: function () {
  2293. return this._depthMask;
  2294. },
  2295. set: function (value) {
  2296. if (this._depthMask === value) {
  2297. return;
  2298. }
  2299. this._depthMask = value;
  2300. this._isDepthMaskDirty = true;
  2301. },
  2302. enumerable: true,
  2303. configurable: true
  2304. });
  2305. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2306. get: function () {
  2307. return this._depthTest;
  2308. },
  2309. set: function (value) {
  2310. if (this._depthTest === value) {
  2311. return;
  2312. }
  2313. this._depthTest = value;
  2314. this._isDepthTestDirty = true;
  2315. },
  2316. enumerable: true,
  2317. configurable: true
  2318. });
  2319. _DepthCullingState.prototype.reset = function () {
  2320. this._depthMask = true;
  2321. this._depthTest = true;
  2322. this._depthFunc = null;
  2323. this._cull = null;
  2324. this._cullFace = null;
  2325. this._isDepthTestDirty = true;
  2326. this._isDepthMaskDirty = true;
  2327. this._isDepthFuncDirty = false;
  2328. this._isCullFaceDirty = false;
  2329. this._isCullDirty = false;
  2330. };
  2331. _DepthCullingState.prototype.apply = function (gl) {
  2332. if (!this.isDirty) {
  2333. return;
  2334. }
  2335. if (this._isCullDirty) {
  2336. if (this.cull === true) {
  2337. gl.enable(gl.CULL_FACE);
  2338. } else if (this.cull === false) {
  2339. gl.disable(gl.CULL_FACE);
  2340. }
  2341. this._isCullDirty = false;
  2342. }
  2343. if (this._isCullFaceDirty) {
  2344. gl.cullFace(this.cullFace);
  2345. this._isCullFaceDirty = false;
  2346. }
  2347. if (this._isDepthMaskDirty) {
  2348. gl.depthMask(this.depthMask);
  2349. this._isDepthMaskDirty = false;
  2350. }
  2351. if (this._isDepthTestDirty) {
  2352. if (this.depthTest === true) {
  2353. gl.enable(gl.DEPTH_TEST);
  2354. } else if (this.depthTest === false) {
  2355. gl.disable(gl.DEPTH_TEST);
  2356. }
  2357. this._isDepthTestDirty = false;
  2358. }
  2359. if (this._isDepthFuncDirty) {
  2360. gl.depthFunc(this.depthFunc);
  2361. this._isDepthFuncDirty = false;
  2362. }
  2363. };
  2364. return _DepthCullingState;
  2365. })();
  2366. BABYLON._DepthCullingState = _DepthCullingState;
  2367. var _AlphaState = (function () {
  2368. function _AlphaState() {
  2369. this._isAlphaBlendDirty = false;
  2370. this._isBlendFunctionParametersDirty = false;
  2371. this._alphaBlend = false;
  2372. this._blendFunctionParameters = new Array(4);
  2373. }
  2374. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2375. get: function () {
  2376. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2377. },
  2378. enumerable: true,
  2379. configurable: true
  2380. });
  2381. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2382. get: function () {
  2383. return this._alphaBlend;
  2384. },
  2385. set: function (value) {
  2386. if (this._alphaBlend === value) {
  2387. return;
  2388. }
  2389. this._alphaBlend = value;
  2390. this._isAlphaBlendDirty = true;
  2391. },
  2392. enumerable: true,
  2393. configurable: true
  2394. });
  2395. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2396. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2397. return;
  2398. }
  2399. this._blendFunctionParameters[0] = value0;
  2400. this._blendFunctionParameters[1] = value1;
  2401. this._blendFunctionParameters[2] = value2;
  2402. this._blendFunctionParameters[3] = value3;
  2403. this._isBlendFunctionParametersDirty = true;
  2404. };
  2405. _AlphaState.prototype.reset = function () {
  2406. this._alphaBlend = false;
  2407. this._blendFunctionParameters[0] = null;
  2408. this._blendFunctionParameters[1] = null;
  2409. this._blendFunctionParameters[2] = null;
  2410. this._blendFunctionParameters[3] = null;
  2411. this._isAlphaBlendDirty = true;
  2412. this._isBlendFunctionParametersDirty = false;
  2413. };
  2414. _AlphaState.prototype.apply = function (gl) {
  2415. if (!this.isDirty) {
  2416. return;
  2417. }
  2418. if (this._isAlphaBlendDirty) {
  2419. if (this._alphaBlend === true) {
  2420. gl.enable(gl.BLEND);
  2421. } else if (this._alphaBlend === false) {
  2422. gl.disable(gl.BLEND);
  2423. }
  2424. this._isAlphaBlendDirty = false;
  2425. }
  2426. if (this._isBlendFunctionParametersDirty) {
  2427. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2428. this._isBlendFunctionParametersDirty = false;
  2429. }
  2430. };
  2431. return _AlphaState;
  2432. })();
  2433. BABYLON._AlphaState = _AlphaState;
  2434. var compileShader = function (gl, source, type, defines) {
  2435. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2436. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2437. gl.compileShader(shader);
  2438. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2439. throw new Error(gl.getShaderInfoLog(shader));
  2440. }
  2441. return shader;
  2442. };
  2443. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2444. var magFilter = gl.NEAREST;
  2445. var minFilter = gl.NEAREST;
  2446. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2447. magFilter = gl.LINEAR;
  2448. if (generateMipMaps) {
  2449. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2450. } else {
  2451. minFilter = gl.LINEAR;
  2452. }
  2453. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2454. magFilter = gl.LINEAR;
  2455. if (generateMipMaps) {
  2456. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2457. } else {
  2458. minFilter = gl.LINEAR;
  2459. }
  2460. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2461. magFilter = gl.NEAREST;
  2462. if (generateMipMaps) {
  2463. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2464. } else {
  2465. minFilter = gl.NEAREST;
  2466. }
  2467. }
  2468. return {
  2469. min: minFilter,
  2470. mag: magFilter
  2471. };
  2472. };
  2473. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2474. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2475. var engine = scene.getEngine();
  2476. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2477. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2478. gl.bindTexture(gl.TEXTURE_2D, texture);
  2479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2480. processFunction(potWidth, potHeight);
  2481. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2484. if (!noMipmap && !isCompressed) {
  2485. gl.generateMipmap(gl.TEXTURE_2D);
  2486. }
  2487. gl.bindTexture(gl.TEXTURE_2D, null);
  2488. engine._activeTexturesCache = [];
  2489. texture._baseWidth = width;
  2490. texture._baseHeight = height;
  2491. texture._width = potWidth;
  2492. texture._height = potHeight;
  2493. texture.isReady = true;
  2494. scene._removePendingData(texture);
  2495. };
  2496. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2497. var img;
  2498. var onload = function () {
  2499. loadedImages.push(img);
  2500. scene._removePendingData(img);
  2501. if (index != extensions.length - 1) {
  2502. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2503. } else {
  2504. onfinish(loadedImages);
  2505. }
  2506. };
  2507. var onerror = function () {
  2508. scene._removePendingData(img);
  2509. };
  2510. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2511. scene._addPendingData(img);
  2512. };
  2513. var EngineCapabilities = (function () {
  2514. function EngineCapabilities() {
  2515. }
  2516. return EngineCapabilities;
  2517. })();
  2518. BABYLON.EngineCapabilities = EngineCapabilities;
  2519. var Engine = (function () {
  2520. function Engine(canvas, antialias, options) {
  2521. var _this = this;
  2522. this.isFullscreen = false;
  2523. this.isPointerLock = false;
  2524. this.forceWireframe = false;
  2525. this.cullBackFaces = true;
  2526. this.renderEvenInBackground = true;
  2527. this.scenes = new Array();
  2528. this._windowIsBackground = false;
  2529. this._runningLoop = false;
  2530. this._loadingDivBackgroundColor = "black";
  2531. this._depthCullingState = new _DepthCullingState();
  2532. this._alphaState = new _AlphaState();
  2533. this._loadedTexturesCache = new Array();
  2534. this._activeTexturesCache = new Array();
  2535. this._compiledEffects = {};
  2536. this._renderingCanvas = canvas;
  2537. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2538. options = options || {};
  2539. options.antialias = antialias;
  2540. try {
  2541. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2542. } catch (e) {
  2543. throw new Error("WebGL not supported");
  2544. }
  2545. if (!this._gl) {
  2546. throw new Error("WebGL not supported");
  2547. }
  2548. this._onBlur = function () {
  2549. _this._windowIsBackground = true;
  2550. };
  2551. this._onFocus = function () {
  2552. _this._windowIsBackground = false;
  2553. };
  2554. window.addEventListener("blur", this._onBlur);
  2555. window.addEventListener("focus", this._onFocus);
  2556. this._workingCanvas = document.createElement("canvas");
  2557. this._workingContext = this._workingCanvas.getContext("2d");
  2558. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2559. this.resize();
  2560. this._caps = new EngineCapabilities();
  2561. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2562. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2563. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2564. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2565. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2566. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2567. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2568. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  2569. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2570. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2571. this.setDepthBuffer(true);
  2572. this.setDepthFunctionToLessOrEqual();
  2573. this.setDepthWrite(true);
  2574. this._onFullscreenChange = function () {
  2575. if (document.fullscreen !== undefined) {
  2576. _this.isFullscreen = document.fullscreen;
  2577. } else if (document.mozFullScreen !== undefined) {
  2578. _this.isFullscreen = document.mozFullScreen;
  2579. } else if (document.webkitIsFullScreen !== undefined) {
  2580. _this.isFullscreen = document.webkitIsFullScreen;
  2581. } else if (document.msIsFullScreen !== undefined) {
  2582. _this.isFullscreen = document.msIsFullScreen;
  2583. }
  2584. if (_this.isFullscreen && _this._pointerLockRequested) {
  2585. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2586. if (canvas.requestPointerLock) {
  2587. canvas.requestPointerLock();
  2588. }
  2589. }
  2590. };
  2591. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2592. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2593. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2594. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2595. this._onPointerLockChange = function () {
  2596. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2597. };
  2598. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2599. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2600. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2601. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2602. }
  2603. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2604. get: function () {
  2605. return Engine._ALPHA_DISABLE;
  2606. },
  2607. enumerable: true,
  2608. configurable: true
  2609. });
  2610. Object.defineProperty(Engine, "ALPHA_ADD", {
  2611. get: function () {
  2612. return Engine._ALPHA_ADD;
  2613. },
  2614. enumerable: true,
  2615. configurable: true
  2616. });
  2617. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2618. get: function () {
  2619. return Engine._ALPHA_COMBINE;
  2620. },
  2621. enumerable: true,
  2622. configurable: true
  2623. });
  2624. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2625. get: function () {
  2626. return Engine._DELAYLOADSTATE_NONE;
  2627. },
  2628. enumerable: true,
  2629. configurable: true
  2630. });
  2631. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2632. get: function () {
  2633. return Engine._DELAYLOADSTATE_LOADED;
  2634. },
  2635. enumerable: true,
  2636. configurable: true
  2637. });
  2638. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2639. get: function () {
  2640. return Engine._DELAYLOADSTATE_LOADING;
  2641. },
  2642. enumerable: true,
  2643. configurable: true
  2644. });
  2645. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2646. get: function () {
  2647. return Engine._DELAYLOADSTATE_NOTLOADED;
  2648. },
  2649. enumerable: true,
  2650. configurable: true
  2651. });
  2652. Object.defineProperty(Engine, "Version", {
  2653. get: function () {
  2654. return "1.14.0";
  2655. },
  2656. enumerable: true,
  2657. configurable: true
  2658. });
  2659. Engine.prototype.getAspectRatio = function (camera) {
  2660. var viewport = camera.viewport;
  2661. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2662. };
  2663. Engine.prototype.getRenderWidth = function () {
  2664. if (this._currentRenderTarget) {
  2665. return this._currentRenderTarget._width;
  2666. }
  2667. return this._renderingCanvas.width;
  2668. };
  2669. Engine.prototype.getRenderHeight = function () {
  2670. if (this._currentRenderTarget) {
  2671. return this._currentRenderTarget._height;
  2672. }
  2673. return this._renderingCanvas.height;
  2674. };
  2675. Engine.prototype.getRenderingCanvas = function () {
  2676. return this._renderingCanvas;
  2677. };
  2678. Engine.prototype.getRenderingCanvasClientRect = function () {
  2679. return this._renderingCanvas.getBoundingClientRect();
  2680. };
  2681. Engine.prototype.setHardwareScalingLevel = function (level) {
  2682. this._hardwareScalingLevel = level;
  2683. this.resize();
  2684. };
  2685. Engine.prototype.getHardwareScalingLevel = function () {
  2686. return this._hardwareScalingLevel;
  2687. };
  2688. Engine.prototype.getLoadedTexturesCache = function () {
  2689. return this._loadedTexturesCache;
  2690. };
  2691. Engine.prototype.getCaps = function () {
  2692. return this._caps;
  2693. };
  2694. Engine.prototype.setDepthFunctionToGreater = function () {
  2695. this._depthCullingState.depthFunc = this._gl.GREATER;
  2696. };
  2697. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2698. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2699. };
  2700. Engine.prototype.setDepthFunctionToLess = function () {
  2701. this._depthCullingState.depthFunc = this._gl.LESS;
  2702. };
  2703. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2704. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2705. };
  2706. Engine.prototype.stopRenderLoop = function () {
  2707. this._renderFunction = null;
  2708. this._runningLoop = false;
  2709. };
  2710. Engine.prototype._renderLoop = function () {
  2711. var _this = this;
  2712. var shouldRender = true;
  2713. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2714. shouldRender = false;
  2715. }
  2716. if (shouldRender) {
  2717. this.beginFrame();
  2718. if (this._renderFunction) {
  2719. this._renderFunction();
  2720. }
  2721. this.endFrame();
  2722. }
  2723. if (this._runningLoop) {
  2724. BABYLON.Tools.QueueNewFrame(function () {
  2725. _this._renderLoop();
  2726. });
  2727. }
  2728. };
  2729. Engine.prototype.runRenderLoop = function (renderFunction) {
  2730. var _this = this;
  2731. this._runningLoop = true;
  2732. this._renderFunction = renderFunction;
  2733. BABYLON.Tools.QueueNewFrame(function () {
  2734. _this._renderLoop();
  2735. });
  2736. };
  2737. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2738. if (this.isFullscreen) {
  2739. BABYLON.Tools.ExitFullscreen();
  2740. } else {
  2741. this._pointerLockRequested = requestPointerLock;
  2742. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2743. }
  2744. };
  2745. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2746. this.applyStates();
  2747. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2748. if (this._depthCullingState.depthMask) {
  2749. this._gl.clearDepth(1.0);
  2750. }
  2751. var mode = 0;
  2752. if (backBuffer)
  2753. mode |= this._gl.COLOR_BUFFER_BIT;
  2754. if (depthStencil && this._depthCullingState.depthMask)
  2755. mode |= this._gl.DEPTH_BUFFER_BIT;
  2756. this._gl.clear(mode);
  2757. };
  2758. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2759. var width = requiredWidth || this._renderingCanvas.width;
  2760. var height = requiredHeight || this._renderingCanvas.height;
  2761. var x = viewport.x || 0;
  2762. var y = viewport.y || 0;
  2763. this._cachedViewport = viewport;
  2764. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2765. };
  2766. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2767. this._cachedViewport = null;
  2768. this._gl.viewport(x, y, width, height);
  2769. };
  2770. Engine.prototype.beginFrame = function () {
  2771. BABYLON.Tools._MeasureFps();
  2772. };
  2773. Engine.prototype.endFrame = function () {
  2774. this.flushFramebuffer();
  2775. };
  2776. Engine.prototype.resize = function () {
  2777. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2778. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2779. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2780. };
  2781. Engine.prototype.bindFramebuffer = function (texture) {
  2782. this._currentRenderTarget = texture;
  2783. var gl = this._gl;
  2784. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2785. this._gl.viewport(0, 0, texture._width, texture._height);
  2786. this.wipeCaches();
  2787. };
  2788. Engine.prototype.unBindFramebuffer = function (texture) {
  2789. this._currentRenderTarget = null;
  2790. if (texture.generateMipMaps) {
  2791. var gl = this._gl;
  2792. gl.bindTexture(gl.TEXTURE_2D, texture);
  2793. gl.generateMipmap(gl.TEXTURE_2D);
  2794. gl.bindTexture(gl.TEXTURE_2D, null);
  2795. }
  2796. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2797. };
  2798. Engine.prototype.flushFramebuffer = function () {
  2799. this._gl.flush();
  2800. };
  2801. Engine.prototype.restoreDefaultFramebuffer = function () {
  2802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2803. this.setViewport(this._cachedViewport);
  2804. this.wipeCaches();
  2805. };
  2806. Engine.prototype._resetVertexBufferBinding = function () {
  2807. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2808. this._cachedVertexBuffers = null;
  2809. };
  2810. Engine.prototype.createVertexBuffer = function (vertices) {
  2811. var vbo = this._gl.createBuffer();
  2812. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2813. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2814. this._resetVertexBufferBinding();
  2815. vbo.references = 1;
  2816. return vbo;
  2817. };
  2818. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2819. var vbo = this._gl.createBuffer();
  2820. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2821. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2822. this._resetVertexBufferBinding();
  2823. vbo.references = 1;
  2824. return vbo;
  2825. };
  2826. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2827. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2828. if (vertices instanceof Float32Array) {
  2829. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2830. } else {
  2831. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2832. }
  2833. this._resetVertexBufferBinding();
  2834. };
  2835. Engine.prototype._resetIndexBufferBinding = function () {
  2836. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2837. this._cachedIndexBuffer = null;
  2838. };
  2839. Engine.prototype.createIndexBuffer = function (indices) {
  2840. var vbo = this._gl.createBuffer();
  2841. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2842. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2843. this._resetIndexBufferBinding();
  2844. vbo.references = 1;
  2845. return vbo;
  2846. };
  2847. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2848. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2849. this._cachedVertexBuffers = vertexBuffer;
  2850. this._cachedEffectForVertexBuffers = effect;
  2851. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2852. var offset = 0;
  2853. for (var index = 0; index < vertexDeclaration.length; index++) {
  2854. var order = effect.getAttributeLocation(index);
  2855. if (order >= 0) {
  2856. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2857. }
  2858. offset += vertexDeclaration[index] * 4;
  2859. }
  2860. }
  2861. if (this._cachedIndexBuffer !== indexBuffer) {
  2862. this._cachedIndexBuffer = indexBuffer;
  2863. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2864. }
  2865. };
  2866. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2867. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2868. this._cachedVertexBuffers = vertexBuffers;
  2869. this._cachedEffectForVertexBuffers = effect;
  2870. var attributes = effect.getAttributesNames();
  2871. for (var index = 0; index < attributes.length; index++) {
  2872. var order = effect.getAttributeLocation(index);
  2873. if (order >= 0) {
  2874. var vertexBuffer = vertexBuffers[attributes[index]];
  2875. if (!vertexBuffer) {
  2876. continue;
  2877. }
  2878. var stride = vertexBuffer.getStrideSize();
  2879. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2880. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2881. }
  2882. }
  2883. }
  2884. if (this._cachedIndexBuffer !== indexBuffer) {
  2885. this._cachedIndexBuffer = indexBuffer;
  2886. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2887. }
  2888. };
  2889. Engine.prototype._releaseBuffer = function (buffer) {
  2890. buffer.references--;
  2891. if (buffer.references === 0) {
  2892. this._gl.deleteBuffer(buffer);
  2893. return true;
  2894. }
  2895. return false;
  2896. };
  2897. Engine.prototype.createInstancesBuffer = function (capacity) {
  2898. var buffer = this._gl.createBuffer();
  2899. buffer.capacity = capacity;
  2900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2901. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2902. return buffer;
  2903. };
  2904. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2905. this._gl.deleteBuffer(buffer);
  2906. };
  2907. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2909. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2910. for (var index = 0; index < 4; index++) {
  2911. var offsetLocation = offsetLocations[index];
  2912. this._gl.enableVertexAttribArray(offsetLocation);
  2913. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2914. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2915. }
  2916. };
  2917. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2919. for (var index = 0; index < 4; index++) {
  2920. var offsetLocation = offsetLocations[index];
  2921. this._gl.disableVertexAttribArray(offsetLocation);
  2922. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2923. }
  2924. };
  2925. Engine.prototype.applyStates = function () {
  2926. this._depthCullingState.apply(this._gl);
  2927. this._alphaState.apply(this._gl);
  2928. };
  2929. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2930. this.applyStates();
  2931. if (instancesCount) {
  2932. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2933. return;
  2934. }
  2935. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2936. };
  2937. Engine.prototype._releaseEffect = function (effect) {
  2938. if (this._compiledEffects[effect._key]) {
  2939. delete this._compiledEffects[effect._key];
  2940. if (effect.getProgram()) {
  2941. this._gl.deleteProgram(effect.getProgram());
  2942. }
  2943. }
  2944. };
  2945. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2946. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2947. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2948. var name = vertex + "+" + fragment + "@" + defines;
  2949. if (this._compiledEffects[name]) {
  2950. return this._compiledEffects[name];
  2951. }
  2952. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2953. effect._key = name;
  2954. this._compiledEffects[name] = effect;
  2955. return effect;
  2956. };
  2957. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2958. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2959. if (typeof samplers === "undefined") { samplers = []; }
  2960. if (typeof defines === "undefined") { defines = ""; }
  2961. return this.createEffect({
  2962. vertex: "particles",
  2963. fragmentElement: fragmentName
  2964. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2965. };
  2966. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2967. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2968. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2969. var shaderProgram = this._gl.createProgram();
  2970. this._gl.attachShader(shaderProgram, vertexShader);
  2971. this._gl.attachShader(shaderProgram, fragmentShader);
  2972. this._gl.linkProgram(shaderProgram);
  2973. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2974. if (!linked) {
  2975. var error = this._gl.getProgramInfoLog(shaderProgram);
  2976. if (error) {
  2977. throw new Error(error);
  2978. }
  2979. }
  2980. this._gl.deleteShader(vertexShader);
  2981. this._gl.deleteShader(fragmentShader);
  2982. return shaderProgram;
  2983. };
  2984. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2985. var results = [];
  2986. for (var index = 0; index < uniformsNames.length; index++) {
  2987. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2988. }
  2989. return results;
  2990. };
  2991. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2992. var results = [];
  2993. for (var index = 0; index < attributesNames.length; index++) {
  2994. try {
  2995. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2996. } catch (e) {
  2997. results.push(-1);
  2998. }
  2999. }
  3000. return results;
  3001. };
  3002. Engine.prototype.enableEffect = function (effect) {
  3003. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3004. return;
  3005. }
  3006. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3007. this._gl.useProgram(effect.getProgram());
  3008. for (var i in this._vertexAttribArrays) {
  3009. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3010. continue;
  3011. }
  3012. this._vertexAttribArrays[i] = false;
  3013. this._gl.disableVertexAttribArray(i);
  3014. }
  3015. var attributesCount = effect.getAttributesCount();
  3016. for (var index = 0; index < attributesCount; index++) {
  3017. var order = effect.getAttributeLocation(index);
  3018. if (order >= 0) {
  3019. this._vertexAttribArrays[order] = true;
  3020. this._gl.enableVertexAttribArray(order);
  3021. }
  3022. }
  3023. this._currentEffect = effect;
  3024. };
  3025. Engine.prototype.setArray = function (uniform, array) {
  3026. if (!uniform)
  3027. return;
  3028. this._gl.uniform1fv(uniform, array);
  3029. };
  3030. Engine.prototype.setMatrices = function (uniform, matrices) {
  3031. if (!uniform)
  3032. return;
  3033. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3034. };
  3035. Engine.prototype.setMatrix = function (uniform, matrix) {
  3036. if (!uniform)
  3037. return;
  3038. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3039. };
  3040. Engine.prototype.setFloat = function (uniform, value) {
  3041. if (!uniform)
  3042. return;
  3043. this._gl.uniform1f(uniform, value);
  3044. };
  3045. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3046. if (!uniform)
  3047. return;
  3048. this._gl.uniform2f(uniform, x, y);
  3049. };
  3050. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3051. if (!uniform)
  3052. return;
  3053. this._gl.uniform3f(uniform, x, y, z);
  3054. };
  3055. Engine.prototype.setBool = function (uniform, bool) {
  3056. if (!uniform)
  3057. return;
  3058. this._gl.uniform1i(uniform, bool);
  3059. };
  3060. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3061. if (!uniform)
  3062. return;
  3063. this._gl.uniform4f(uniform, x, y, z, w);
  3064. };
  3065. Engine.prototype.setColor3 = function (uniform, color3) {
  3066. if (!uniform)
  3067. return;
  3068. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3069. };
  3070. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3071. if (!uniform)
  3072. return;
  3073. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3074. };
  3075. Engine.prototype.setState = function (culling, force) {
  3076. if (this._depthCullingState.cull !== culling || force) {
  3077. if (culling) {
  3078. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3079. this._depthCullingState.cull = true;
  3080. } else {
  3081. this._depthCullingState.cull = false;
  3082. }
  3083. }
  3084. };
  3085. Engine.prototype.setDepthBuffer = function (enable) {
  3086. this._depthCullingState.depthTest = enable;
  3087. };
  3088. Engine.prototype.getDepthWrite = function () {
  3089. return this._depthCullingState.depthMask;
  3090. };
  3091. Engine.prototype.setDepthWrite = function (enable) {
  3092. this._depthCullingState.depthMask = enable;
  3093. };
  3094. Engine.prototype.setColorWrite = function (enable) {
  3095. this._gl.colorMask(enable, enable, enable, enable);
  3096. };
  3097. Engine.prototype.setAlphaMode = function (mode) {
  3098. switch (mode) {
  3099. case BABYLON.Engine.ALPHA_DISABLE:
  3100. this.setDepthWrite(true);
  3101. this._alphaState.alphaBlend = false;
  3102. break;
  3103. case BABYLON.Engine.ALPHA_COMBINE:
  3104. this.setDepthWrite(false);
  3105. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3106. this._alphaState.alphaBlend = true;
  3107. break;
  3108. case BABYLON.Engine.ALPHA_ADD:
  3109. this.setDepthWrite(false);
  3110. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3111. this._alphaState.alphaBlend = true;
  3112. break;
  3113. }
  3114. };
  3115. Engine.prototype.setAlphaTesting = function (enable) {
  3116. this._alphaTest = enable;
  3117. };
  3118. Engine.prototype.getAlphaTesting = function () {
  3119. return this._alphaTest;
  3120. };
  3121. Engine.prototype.wipeCaches = function () {
  3122. this._activeTexturesCache = [];
  3123. this._currentEffect = null;
  3124. this._depthCullingState.reset();
  3125. this._alphaState.reset();
  3126. this._cachedVertexBuffers = null;
  3127. this._cachedIndexBuffer = null;
  3128. this._cachedEffectForVertexBuffers = null;
  3129. };
  3130. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3131. var gl = this._gl;
  3132. gl.bindTexture(gl.TEXTURE_2D, texture);
  3133. var magFilter = gl.NEAREST;
  3134. var minFilter = gl.NEAREST;
  3135. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3136. magFilter = gl.LINEAR;
  3137. minFilter = gl.LINEAR;
  3138. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3139. magFilter = gl.LINEAR;
  3140. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3141. }
  3142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3144. gl.bindTexture(gl.TEXTURE_2D, null);
  3145. };
  3146. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError) {
  3147. var _this = this;
  3148. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3149. if (typeof onLoad === "undefined") { onLoad = null; }
  3150. if (typeof onError === "undefined") { onError = null; }
  3151. var texture = this._gl.createTexture();
  3152. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3153. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3154. var isTGA = (extension === ".tga");
  3155. scene._addPendingData(texture);
  3156. texture.url = url;
  3157. texture.noMipmap = noMipmap;
  3158. texture.references = 1;
  3159. this._loadedTexturesCache.push(texture);
  3160. var onerror = function () {
  3161. scene._removePendingData(texture);
  3162. if (onError) {
  3163. onError();
  3164. }
  3165. };
  3166. if (isTGA) {
  3167. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3168. var data = new Uint8Array(arrayBuffer);
  3169. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3170. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3171. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3172. if (onLoad) {
  3173. onLoad();
  3174. }
  3175. }, samplingMode);
  3176. }, onerror, scene.database, true);
  3177. } else if (isDDS) {
  3178. BABYLON.Tools.LoadFile(url, function (data) {
  3179. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3180. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3181. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3182. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3183. if (onLoad) {
  3184. onLoad();
  3185. }
  3186. }, samplingMode);
  3187. }, onerror, scene.database, true);
  3188. } else {
  3189. var onload = function (img) {
  3190. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3191. var isPot = (img.width == potWidth && img.height == potHeight);
  3192. if (!isPot) {
  3193. _this._workingCanvas.width = potWidth;
  3194. _this._workingCanvas.height = potHeight;
  3195. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3196. }
  3197. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3198. if (onLoad) {
  3199. onLoad();
  3200. }
  3201. }, samplingMode);
  3202. };
  3203. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3204. }
  3205. return texture;
  3206. };
  3207. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3208. var texture = this._gl.createTexture();
  3209. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3210. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3211. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3212. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3213. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3214. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3215. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3216. this._activeTexturesCache = [];
  3217. texture._baseWidth = width;
  3218. texture._baseHeight = height;
  3219. texture._width = width;
  3220. texture._height = height;
  3221. texture.isReady = false;
  3222. texture.generateMipMaps = generateMipMaps;
  3223. texture.references = 1;
  3224. this._loadedTexturesCache.push(texture);
  3225. return texture;
  3226. };
  3227. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3228. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3229. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3230. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3231. if (texture.generateMipMaps) {
  3232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3233. }
  3234. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3235. this._activeTexturesCache = [];
  3236. texture.isReady = true;
  3237. };
  3238. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3239. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3240. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3241. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3242. if (!texture._workingCanvas) {
  3243. texture._workingCanvas = document.createElement("canvas");
  3244. texture._workingContext = texture._workingCanvas.getContext("2d");
  3245. texture._workingCanvas.width = texture._width;
  3246. texture._workingCanvas.height = texture._height;
  3247. }
  3248. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3249. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3250. } else {
  3251. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3252. }
  3253. if (texture.generateMipMaps) {
  3254. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3255. }
  3256. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3257. this._activeTexturesCache = [];
  3258. texture.isReady = true;
  3259. };
  3260. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3261. var generateMipMaps = false;
  3262. var generateDepthBuffer = true;
  3263. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3264. if (options !== undefined) {
  3265. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3266. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3267. if (options.samplingMode !== undefined) {
  3268. samplingMode = options.samplingMode;
  3269. }
  3270. }
  3271. var gl = this._gl;
  3272. var texture = gl.createTexture();
  3273. gl.bindTexture(gl.TEXTURE_2D, texture);
  3274. var width = size.width || size;
  3275. var height = size.height || size;
  3276. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3281. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3282. var depthBuffer;
  3283. if (generateDepthBuffer) {
  3284. depthBuffer = gl.createRenderbuffer();
  3285. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3286. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3287. }
  3288. var framebuffer = gl.createFramebuffer();
  3289. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3290. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3291. if (generateDepthBuffer) {
  3292. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3293. }
  3294. gl.bindTexture(gl.TEXTURE_2D, null);
  3295. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3296. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3297. texture._framebuffer = framebuffer;
  3298. if (generateDepthBuffer) {
  3299. texture._depthBuffer = depthBuffer;
  3300. }
  3301. texture._width = width;
  3302. texture._height = height;
  3303. texture.isReady = true;
  3304. texture.generateMipMaps = generateMipMaps;
  3305. texture.references = 1;
  3306. this._activeTexturesCache = [];
  3307. this._loadedTexturesCache.push(texture);
  3308. return texture;
  3309. };
  3310. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3311. var _this = this;
  3312. var gl = this._gl;
  3313. var texture = gl.createTexture();
  3314. texture.isCube = true;
  3315. texture.url = rootUrl;
  3316. texture.references = 1;
  3317. this._loadedTexturesCache.push(texture);
  3318. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3319. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3320. if (isDDS) {
  3321. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3322. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3323. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3324. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3325. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3326. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3327. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3328. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3329. }
  3330. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3331. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3332. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3334. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3335. _this._activeTexturesCache = [];
  3336. texture._width = info.width;
  3337. texture._height = info.height;
  3338. texture.isReady = true;
  3339. }, null, null, true);
  3340. } else {
  3341. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3342. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3343. var height = width;
  3344. _this._workingCanvas.width = width;
  3345. _this._workingCanvas.height = height;
  3346. var faces = [
  3347. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3348. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3349. ];
  3350. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3351. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3352. for (var index = 0; index < faces.length; index++) {
  3353. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3354. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3355. }
  3356. if (!noMipmap) {
  3357. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3358. }
  3359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3363. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3364. _this._activeTexturesCache = [];
  3365. texture._width = width;
  3366. texture._height = height;
  3367. texture.isReady = true;
  3368. }, extensions);
  3369. }
  3370. return texture;
  3371. };
  3372. Engine.prototype._releaseTexture = function (texture) {
  3373. var gl = this._gl;
  3374. if (texture._framebuffer) {
  3375. gl.deleteFramebuffer(texture._framebuffer);
  3376. }
  3377. if (texture._depthBuffer) {
  3378. gl.deleteRenderbuffer(texture._depthBuffer);
  3379. }
  3380. gl.deleteTexture(texture);
  3381. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3382. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3383. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3384. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3385. this._activeTexturesCache[channel] = null;
  3386. }
  3387. var index = this._loadedTexturesCache.indexOf(texture);
  3388. if (index !== -1) {
  3389. this._loadedTexturesCache.splice(index, 1);
  3390. }
  3391. };
  3392. Engine.prototype.bindSamplers = function (effect) {
  3393. this._gl.useProgram(effect.getProgram());
  3394. var samplers = effect.getSamplers();
  3395. for (var index = 0; index < samplers.length; index++) {
  3396. var uniform = effect.getUniform(samplers[index]);
  3397. this._gl.uniform1i(uniform, index);
  3398. }
  3399. this._currentEffect = null;
  3400. };
  3401. Engine.prototype._bindTexture = function (channel, texture) {
  3402. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3403. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3404. this._activeTexturesCache[channel] = null;
  3405. };
  3406. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3407. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3408. };
  3409. Engine.prototype.setTexture = function (channel, texture) {
  3410. if (channel < 0) {
  3411. return;
  3412. }
  3413. if (!texture || !texture.isReady()) {
  3414. if (this._activeTexturesCache[channel] != null) {
  3415. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3416. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3417. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3418. this._activeTexturesCache[channel] = null;
  3419. }
  3420. return;
  3421. }
  3422. if (texture instanceof BABYLON.VideoTexture) {
  3423. if (texture.update()) {
  3424. this._activeTexturesCache[channel] = null;
  3425. }
  3426. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3427. texture.delayLoad();
  3428. return;
  3429. }
  3430. if (this._activeTexturesCache[channel] == texture) {
  3431. return;
  3432. }
  3433. this._activeTexturesCache[channel] = texture;
  3434. var internalTexture = texture.getInternalTexture();
  3435. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3436. if (internalTexture.isCube) {
  3437. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3438. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3439. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3440. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3441. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3442. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3443. }
  3444. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3445. } else {
  3446. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3447. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3448. internalTexture._cachedWrapU = texture.wrapU;
  3449. switch (texture.wrapU) {
  3450. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3451. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3452. break;
  3453. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3454. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3455. break;
  3456. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3457. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3458. break;
  3459. }
  3460. }
  3461. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3462. internalTexture._cachedWrapV = texture.wrapV;
  3463. switch (texture.wrapV) {
  3464. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3465. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3466. break;
  3467. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3468. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3469. break;
  3470. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3471. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3472. break;
  3473. }
  3474. }
  3475. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3476. }
  3477. };
  3478. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3479. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3480. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3481. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3482. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3483. }
  3484. };
  3485. Engine.prototype.readPixels = function (x, y, width, height) {
  3486. var data = new Uint8Array(height * width * 4);
  3487. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3488. return data;
  3489. };
  3490. Engine.prototype.dispose = function () {
  3491. this.hideLoadingUI();
  3492. this.stopRenderLoop();
  3493. while (this.scenes.length) {
  3494. this.scenes[0].dispose();
  3495. }
  3496. for (var name in this._compiledEffects) {
  3497. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3498. }
  3499. for (var i in this._vertexAttribArrays) {
  3500. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3501. continue;
  3502. }
  3503. this._gl.disableVertexAttribArray(i);
  3504. }
  3505. window.removeEventListener("blur", this._onBlur);
  3506. window.removeEventListener("focus", this._onFocus);
  3507. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3508. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3509. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3510. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3511. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3512. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3513. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3514. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3515. };
  3516. Engine.prototype.displayLoadingUI = function () {
  3517. var _this = this;
  3518. this._loadingDiv = document.createElement("div");
  3519. this._loadingDiv.style.opacity = "0";
  3520. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3521. this._loadingTextDiv = document.createElement("div");
  3522. this._loadingTextDiv.style.position = "absolute";
  3523. this._loadingTextDiv.style.left = "0";
  3524. this._loadingTextDiv.style.top = "50%";
  3525. this._loadingTextDiv.style.marginTop = "80px";
  3526. this._loadingTextDiv.style.width = "100%";
  3527. this._loadingTextDiv.style.height = "20px";
  3528. this._loadingTextDiv.style.fontFamily = "Arial";
  3529. this._loadingTextDiv.style.fontSize = "14px";
  3530. this._loadingTextDiv.style.color = "white";
  3531. this._loadingTextDiv.style.textAlign = "center";
  3532. this._loadingTextDiv.innerHTML = "Loading";
  3533. this._loadingDiv.appendChild(this._loadingTextDiv);
  3534. var imgBack = new Image();
  3535. 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==";
  3536. imgBack.style.position = "absolute";
  3537. imgBack.style.left = "50%";
  3538. imgBack.style.top = "50%";
  3539. imgBack.style.marginLeft = "-50px";
  3540. imgBack.style.marginTop = "-50px";
  3541. imgBack.style.transition = "transform 1.0s ease";
  3542. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3543. var deg = 360;
  3544. var onTransitionEnd = function () {
  3545. deg += 360;
  3546. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3547. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3548. };
  3549. imgBack.addEventListener("transitionend", onTransitionEnd);
  3550. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3551. this._loadingDiv.appendChild(imgBack);
  3552. var imgFront = new Image();
  3553. 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=";
  3554. imgFront.style.position = "absolute";
  3555. imgFront.style.left = "50%";
  3556. imgFront.style.top = "50%";
  3557. imgFront.style.marginLeft = "-50px";
  3558. imgFront.style.marginTop = "-50px";
  3559. this._loadingDiv.appendChild(imgFront);
  3560. this._resizeLoadingUI = function () {
  3561. var canvasRect = _this.getRenderingCanvasClientRect();
  3562. _this._loadingDiv.style.position = "absolute";
  3563. _this._loadingDiv.style.left = canvasRect.left + "px";
  3564. _this._loadingDiv.style.top = canvasRect.top + "px";
  3565. _this._loadingDiv.style.width = canvasRect.width + "px";
  3566. _this._loadingDiv.style.height = canvasRect.height + "px";
  3567. };
  3568. this._resizeLoadingUI();
  3569. window.addEventListener("resize", this._resizeLoadingUI);
  3570. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3571. document.body.appendChild(this._loadingDiv);
  3572. setTimeout(function () {
  3573. _this._loadingDiv.style.opacity = "1";
  3574. imgBack.style.transform = "rotateZ(360deg)";
  3575. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3576. }, 0);
  3577. };
  3578. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3579. set: function (text) {
  3580. if (!this._loadingDiv) {
  3581. return;
  3582. }
  3583. this._loadingTextDiv.innerHTML = text;
  3584. },
  3585. enumerable: true,
  3586. configurable: true
  3587. });
  3588. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3589. get: function () {
  3590. return this._loadingDivBackgroundColor;
  3591. },
  3592. set: function (color) {
  3593. this._loadingDivBackgroundColor = color;
  3594. if (!this._loadingDiv) {
  3595. return;
  3596. }
  3597. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3598. },
  3599. enumerable: true,
  3600. configurable: true
  3601. });
  3602. Engine.prototype.hideLoadingUI = function () {
  3603. var _this = this;
  3604. if (!this._loadingDiv) {
  3605. return;
  3606. }
  3607. var onTransitionEnd = function () {
  3608. if (!_this._loadingDiv) {
  3609. return;
  3610. }
  3611. document.body.removeChild(_this._loadingDiv);
  3612. window.removeEventListener("resize", _this._resizeLoadingUI);
  3613. _this._loadingDiv = null;
  3614. };
  3615. this._loadingDiv.style.opacity = "0";
  3616. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3617. };
  3618. Engine.isSupported = function () {
  3619. try {
  3620. var tempcanvas = document.createElement("canvas");
  3621. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3622. return gl != null && !!window.WebGLRenderingContext;
  3623. } catch (e) {
  3624. return false;
  3625. }
  3626. };
  3627. Engine._ALPHA_DISABLE = 0;
  3628. Engine._ALPHA_ADD = 1;
  3629. Engine._ALPHA_COMBINE = 2;
  3630. Engine._DELAYLOADSTATE_NONE = 0;
  3631. Engine._DELAYLOADSTATE_LOADED = 1;
  3632. Engine._DELAYLOADSTATE_LOADING = 2;
  3633. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3634. Engine.Epsilon = 0.001;
  3635. Engine.CollisionsEpsilon = 0.001;
  3636. Engine.ShadersRepository = "Babylon/Shaders/";
  3637. return Engine;
  3638. })();
  3639. BABYLON.Engine = Engine;
  3640. })(BABYLON || (BABYLON = {}));
  3641. var BABYLON;
  3642. (function (BABYLON) {
  3643. var Node = (function () {
  3644. function Node(name, scene) {
  3645. this.state = "";
  3646. this.animations = new Array();
  3647. this._childrenFlag = -1;
  3648. this._isEnabled = true;
  3649. this._isReady = true;
  3650. this._currentRenderId = -1;
  3651. this.name = name;
  3652. this.id = name;
  3653. this._scene = scene;
  3654. this._initCache();
  3655. }
  3656. Node.prototype.getScene = function () {
  3657. return this._scene;
  3658. };
  3659. Node.prototype.getEngine = function () {
  3660. return this._scene.getEngine();
  3661. };
  3662. Node.prototype.getWorldMatrix = function () {
  3663. return BABYLON.Matrix.Identity();
  3664. };
  3665. Node.prototype._initCache = function () {
  3666. this._cache = {};
  3667. this._cache.parent = undefined;
  3668. };
  3669. Node.prototype.updateCache = function (force) {
  3670. if (!force && this.isSynchronized())
  3671. return;
  3672. this._cache.parent = this.parent;
  3673. this._updateCache();
  3674. };
  3675. Node.prototype._updateCache = function (ignoreParentClass) {
  3676. };
  3677. Node.prototype._isSynchronized = function () {
  3678. return true;
  3679. };
  3680. Node.prototype.isSynchronizedWithParent = function () {
  3681. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3682. };
  3683. Node.prototype.isSynchronized = function (updateCache) {
  3684. var check = this.hasNewParent();
  3685. check = check || !this.isSynchronizedWithParent();
  3686. check = check || !this._isSynchronized();
  3687. if (updateCache)
  3688. this.updateCache(true);
  3689. return !check;
  3690. };
  3691. Node.prototype.hasNewParent = function (update) {
  3692. if (this._cache.parent === this.parent)
  3693. return false;
  3694. if (update)
  3695. this._cache.parent = this.parent;
  3696. return true;
  3697. };
  3698. Node.prototype.isReady = function () {
  3699. return this._isReady;
  3700. };
  3701. Node.prototype.isEnabled = function () {
  3702. if (!this._isEnabled) {
  3703. return false;
  3704. }
  3705. if (this.parent) {
  3706. return this.parent.isEnabled();
  3707. }
  3708. return true;
  3709. };
  3710. Node.prototype.setEnabled = function (value) {
  3711. this._isEnabled = value;
  3712. };
  3713. Node.prototype.isDescendantOf = function (ancestor) {
  3714. if (this.parent) {
  3715. if (this.parent === ancestor) {
  3716. return true;
  3717. }
  3718. return this.parent.isDescendantOf(ancestor);
  3719. }
  3720. return false;
  3721. };
  3722. Node.prototype._getDescendants = function (list, results) {
  3723. for (var index = 0; index < list.length; index++) {
  3724. var item = list[index];
  3725. if (item.isDescendantOf(this)) {
  3726. results.push(item);
  3727. }
  3728. }
  3729. };
  3730. Node.prototype.getDescendants = function () {
  3731. var results = [];
  3732. this._getDescendants(this._scene.meshes, results);
  3733. this._getDescendants(this._scene.lights, results);
  3734. this._getDescendants(this._scene.cameras, results);
  3735. return results;
  3736. };
  3737. Node.prototype._setReady = function (state) {
  3738. if (state == this._isReady) {
  3739. return;
  3740. }
  3741. if (!state) {
  3742. this._isReady = false;
  3743. return;
  3744. }
  3745. this._isReady = true;
  3746. if (this.onReady) {
  3747. this.onReady(this);
  3748. }
  3749. };
  3750. return Node;
  3751. })();
  3752. BABYLON.Node = Node;
  3753. })(BABYLON || (BABYLON = {}));
  3754. var BABYLON;
  3755. (function (BABYLON) {
  3756. var BoundingSphere = (function () {
  3757. function BoundingSphere(minimum, maximum) {
  3758. this.minimum = minimum;
  3759. this.maximum = maximum;
  3760. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3761. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3762. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3763. this.radius = distance * 0.5;
  3764. this.centerWorld = BABYLON.Vector3.Zero();
  3765. this._update(BABYLON.Matrix.Identity());
  3766. }
  3767. BoundingSphere.prototype._update = function (world) {
  3768. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3769. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3770. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3771. };
  3772. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3773. for (var i = 0; i < 6; i++) {
  3774. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3775. return false;
  3776. }
  3777. return true;
  3778. };
  3779. BoundingSphere.prototype.intersectsPoint = function (point) {
  3780. var x = this.centerWorld.x - point.x;
  3781. var y = this.centerWorld.y - point.y;
  3782. var z = this.centerWorld.z - point.z;
  3783. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3784. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3785. return false;
  3786. return true;
  3787. };
  3788. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3789. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3790. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3791. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3792. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3793. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3794. return false;
  3795. return true;
  3796. };
  3797. return BoundingSphere;
  3798. })();
  3799. BABYLON.BoundingSphere = BoundingSphere;
  3800. })(BABYLON || (BABYLON = {}));
  3801. var BABYLON;
  3802. (function (BABYLON) {
  3803. var BoundingBox = (function () {
  3804. function BoundingBox(minimum, maximum) {
  3805. this.minimum = minimum;
  3806. this.maximum = maximum;
  3807. this.vectors = new Array();
  3808. this.vectorsWorld = new Array();
  3809. this.vectors.push(this.minimum.clone());
  3810. this.vectors.push(this.maximum.clone());
  3811. this.vectors.push(this.minimum.clone());
  3812. this.vectors[2].x = this.maximum.x;
  3813. this.vectors.push(this.minimum.clone());
  3814. this.vectors[3].y = this.maximum.y;
  3815. this.vectors.push(this.minimum.clone());
  3816. this.vectors[4].z = this.maximum.z;
  3817. this.vectors.push(this.maximum.clone());
  3818. this.vectors[5].z = this.minimum.z;
  3819. this.vectors.push(this.maximum.clone());
  3820. this.vectors[6].x = this.minimum.x;
  3821. this.vectors.push(this.maximum.clone());
  3822. this.vectors[7].y = this.minimum.y;
  3823. this.center = this.maximum.add(this.minimum).scale(0.5);
  3824. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3825. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3826. for (var index = 0; index < this.vectors.length; index++) {
  3827. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3828. }
  3829. this.minimumWorld = BABYLON.Vector3.Zero();
  3830. this.maximumWorld = BABYLON.Vector3.Zero();
  3831. this._update(BABYLON.Matrix.Identity());
  3832. }
  3833. BoundingBox.prototype.getWorldMatrix = function () {
  3834. return this._worldMatrix;
  3835. };
  3836. BoundingBox.prototype._update = function (world) {
  3837. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3838. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3839. for (var index = 0; index < this.vectors.length; index++) {
  3840. var v = this.vectorsWorld[index];
  3841. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3842. if (v.x < this.minimumWorld.x)
  3843. this.minimumWorld.x = v.x;
  3844. if (v.y < this.minimumWorld.y)
  3845. this.minimumWorld.y = v.y;
  3846. if (v.z < this.minimumWorld.z)
  3847. this.minimumWorld.z = v.z;
  3848. if (v.x > this.maximumWorld.x)
  3849. this.maximumWorld.x = v.x;
  3850. if (v.y > this.maximumWorld.y)
  3851. this.maximumWorld.y = v.y;
  3852. if (v.z > this.maximumWorld.z)
  3853. this.maximumWorld.z = v.z;
  3854. }
  3855. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3856. this.center.scaleInPlace(0.5);
  3857. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3858. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3859. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3860. this._worldMatrix = world;
  3861. };
  3862. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3863. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3864. };
  3865. BoundingBox.prototype.intersectsPoint = function (point) {
  3866. var delta = BABYLON.Engine.Epsilon;
  3867. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3868. return false;
  3869. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3870. return false;
  3871. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3872. return false;
  3873. return true;
  3874. };
  3875. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3876. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3877. };
  3878. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3879. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3880. return false;
  3881. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3882. return false;
  3883. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3884. return false;
  3885. return true;
  3886. };
  3887. BoundingBox.Intersects = function (box0, box1) {
  3888. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3889. return false;
  3890. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3891. return false;
  3892. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3893. return false;
  3894. return true;
  3895. };
  3896. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3897. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3898. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3899. return (num <= (sphereRadius * sphereRadius));
  3900. };
  3901. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3902. for (var p = 0; p < 6; p++) {
  3903. var inCount = 8;
  3904. for (var i = 0; i < 8; i++) {
  3905. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3906. --inCount;
  3907. } else {
  3908. break;
  3909. }
  3910. }
  3911. if (inCount == 0)
  3912. return false;
  3913. }
  3914. return true;
  3915. };
  3916. return BoundingBox;
  3917. })();
  3918. BABYLON.BoundingBox = BoundingBox;
  3919. })(BABYLON || (BABYLON = {}));
  3920. var BABYLON;
  3921. (function (BABYLON) {
  3922. var computeBoxExtents = function (axis, box) {
  3923. var p = BABYLON.Vector3.Dot(box.center, axis);
  3924. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3925. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3926. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3927. var r = r0 + r1 + r2;
  3928. return {
  3929. min: p - r,
  3930. max: p + r
  3931. };
  3932. };
  3933. var extentsOverlap = function (min0, max0, min1, max1) {
  3934. return !(min0 > max1 || min1 > max0);
  3935. };
  3936. var axisOverlap = function (axis, box0, box1) {
  3937. var result0 = computeBoxExtents(axis, box0);
  3938. var result1 = computeBoxExtents(axis, box1);
  3939. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3940. };
  3941. var BoundingInfo = (function () {
  3942. function BoundingInfo(minimum, maximum) {
  3943. this.minimum = minimum;
  3944. this.maximum = maximum;
  3945. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3946. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3947. }
  3948. BoundingInfo.prototype._update = function (world) {
  3949. this.boundingBox._update(world);
  3950. this.boundingSphere._update(world);
  3951. };
  3952. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3953. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3954. return false;
  3955. return this.boundingBox.isInFrustum(frustumPlanes);
  3956. };
  3957. BoundingInfo.prototype._checkCollision = function (collider) {
  3958. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3959. };
  3960. BoundingInfo.prototype.intersectsPoint = function (point) {
  3961. if (!this.boundingSphere.centerWorld) {
  3962. return false;
  3963. }
  3964. if (!this.boundingSphere.intersectsPoint(point)) {
  3965. return false;
  3966. }
  3967. if (!this.boundingBox.intersectsPoint(point)) {
  3968. return false;
  3969. }
  3970. return true;
  3971. };
  3972. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3973. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3974. return false;
  3975. }
  3976. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3977. return false;
  3978. }
  3979. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3980. return false;
  3981. }
  3982. if (!precise) {
  3983. return true;
  3984. }
  3985. var box0 = this.boundingBox;
  3986. var box1 = boundingInfo.boundingBox;
  3987. if (!axisOverlap(box0.directions[0], box0, box1))
  3988. return false;
  3989. if (!axisOverlap(box0.directions[1], box0, box1))
  3990. return false;
  3991. if (!axisOverlap(box0.directions[2], box0, box1))
  3992. return false;
  3993. if (!axisOverlap(box1.directions[0], box0, box1))
  3994. return false;
  3995. if (!axisOverlap(box1.directions[1], box0, box1))
  3996. return false;
  3997. if (!axisOverlap(box1.directions[2], box0, box1))
  3998. return false;
  3999. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4000. return false;
  4001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4002. return false;
  4003. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4004. return false;
  4005. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4006. return false;
  4007. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4008. return false;
  4009. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4010. return false;
  4011. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4012. return false;
  4013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4014. return false;
  4015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4016. return false;
  4017. return true;
  4018. };
  4019. return BoundingInfo;
  4020. })();
  4021. BABYLON.BoundingInfo = BoundingInfo;
  4022. })(BABYLON || (BABYLON = {}));
  4023. var __extends = this.__extends || function (d, b) {
  4024. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4025. function __() { this.constructor = d; }
  4026. __.prototype = b.prototype;
  4027. d.prototype = new __();
  4028. };
  4029. var BABYLON;
  4030. (function (BABYLON) {
  4031. var Light = (function (_super) {
  4032. __extends(Light, _super);
  4033. function Light(name, scene) {
  4034. _super.call(this, name, scene);
  4035. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4036. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4037. this.intensity = 1.0;
  4038. this.range = Number.MAX_VALUE;
  4039. this.includedOnlyMeshes = new Array();
  4040. this.excludedMeshes = new Array();
  4041. this._excludedMeshesIds = new Array();
  4042. this._includedOnlyMeshesIds = new Array();
  4043. scene.lights.push(this);
  4044. }
  4045. Light.prototype.getShadowGenerator = function () {
  4046. return this._shadowGenerator;
  4047. };
  4048. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4049. };
  4050. Light.prototype._getWorldMatrix = function () {
  4051. return BABYLON.Matrix.Identity();
  4052. };
  4053. Light.prototype.canAffectMesh = function (mesh) {
  4054. if (!mesh) {
  4055. return true;
  4056. }
  4057. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4058. return false;
  4059. }
  4060. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4061. return false;
  4062. }
  4063. return true;
  4064. };
  4065. Light.prototype.getWorldMatrix = function () {
  4066. this._currentRenderId = this.getScene().getRenderId();
  4067. var worldMatrix = this._getWorldMatrix();
  4068. if (this.parent && this.parent.getWorldMatrix) {
  4069. if (!this._parentedWorldMatrix) {
  4070. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4071. }
  4072. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4073. return this._parentedWorldMatrix;
  4074. }
  4075. return worldMatrix;
  4076. };
  4077. Light.prototype.dispose = function () {
  4078. if (this._shadowGenerator) {
  4079. this._shadowGenerator.dispose();
  4080. this._shadowGenerator = null;
  4081. }
  4082. var index = this.getScene().lights.indexOf(this);
  4083. this.getScene().lights.splice(index, 1);
  4084. };
  4085. return Light;
  4086. })(BABYLON.Node);
  4087. BABYLON.Light = Light;
  4088. })(BABYLON || (BABYLON = {}));
  4089. var __extends = this.__extends || function (d, b) {
  4090. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4091. function __() { this.constructor = d; }
  4092. __.prototype = b.prototype;
  4093. d.prototype = new __();
  4094. };
  4095. var BABYLON;
  4096. (function (BABYLON) {
  4097. var PointLight = (function (_super) {
  4098. __extends(PointLight, _super);
  4099. function PointLight(name, position, scene) {
  4100. _super.call(this, name, scene);
  4101. this.position = position;
  4102. }
  4103. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4104. if (this.parent && this.parent.getWorldMatrix) {
  4105. if (!this._transformedPosition) {
  4106. this._transformedPosition = BABYLON.Vector3.Zero();
  4107. }
  4108. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4109. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4110. return;
  4111. }
  4112. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4113. };
  4114. PointLight.prototype.getShadowGenerator = function () {
  4115. return null;
  4116. };
  4117. PointLight.prototype._getWorldMatrix = function () {
  4118. if (!this._worldMatrix) {
  4119. this._worldMatrix = BABYLON.Matrix.Identity();
  4120. }
  4121. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4122. return this._worldMatrix;
  4123. };
  4124. return PointLight;
  4125. })(BABYLON.Light);
  4126. BABYLON.PointLight = PointLight;
  4127. })(BABYLON || (BABYLON = {}));
  4128. var __extends = this.__extends || function (d, b) {
  4129. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4130. function __() { this.constructor = d; }
  4131. __.prototype = b.prototype;
  4132. d.prototype = new __();
  4133. };
  4134. var BABYLON;
  4135. (function (BABYLON) {
  4136. var SpotLight = (function (_super) {
  4137. __extends(SpotLight, _super);
  4138. function SpotLight(name, position, direction, angle, exponent, scene) {
  4139. _super.call(this, name, scene);
  4140. this.position = position;
  4141. this.direction = direction;
  4142. this.angle = angle;
  4143. this.exponent = exponent;
  4144. }
  4145. SpotLight.prototype.setDirectionToTarget = function (target) {
  4146. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4147. return this.direction;
  4148. };
  4149. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4150. var normalizeDirection;
  4151. if (this.parent && this.parent.getWorldMatrix) {
  4152. if (!this._transformedDirection) {
  4153. this._transformedDirection = BABYLON.Vector3.Zero();
  4154. }
  4155. if (!this._transformedPosition) {
  4156. this._transformedPosition = BABYLON.Vector3.Zero();
  4157. }
  4158. var parentWorldMatrix = this.parent.getWorldMatrix();
  4159. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4160. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4161. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4162. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4163. } else {
  4164. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4165. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4166. }
  4167. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4168. };
  4169. SpotLight.prototype._getWorldMatrix = function () {
  4170. if (!this._worldMatrix) {
  4171. this._worldMatrix = BABYLON.Matrix.Identity();
  4172. }
  4173. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4174. return this._worldMatrix;
  4175. };
  4176. return SpotLight;
  4177. })(BABYLON.Light);
  4178. BABYLON.SpotLight = SpotLight;
  4179. })(BABYLON || (BABYLON = {}));
  4180. var __extends = this.__extends || function (d, b) {
  4181. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4182. function __() { this.constructor = d; }
  4183. __.prototype = b.prototype;
  4184. d.prototype = new __();
  4185. };
  4186. var BABYLON;
  4187. (function (BABYLON) {
  4188. var DirectionalLight = (function (_super) {
  4189. __extends(DirectionalLight, _super);
  4190. function DirectionalLight(name, direction, scene) {
  4191. _super.call(this, name, scene);
  4192. this.direction = direction;
  4193. this.position = direction.scale(-1);
  4194. }
  4195. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4196. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4197. return this.direction;
  4198. };
  4199. DirectionalLight.prototype._computeTransformedPosition = function () {
  4200. if (this.parent && this.parent.getWorldMatrix) {
  4201. if (!this._transformedPosition) {
  4202. this._transformedPosition = BABYLON.Vector3.Zero();
  4203. }
  4204. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4205. return true;
  4206. }
  4207. return false;
  4208. };
  4209. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4210. if (this.parent && this.parent.getWorldMatrix) {
  4211. if (!this._transformedDirection) {
  4212. this._transformedDirection = BABYLON.Vector3.Zero();
  4213. }
  4214. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4215. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4216. return;
  4217. }
  4218. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4219. };
  4220. DirectionalLight.prototype._getWorldMatrix = function () {
  4221. if (!this._worldMatrix) {
  4222. this._worldMatrix = BABYLON.Matrix.Identity();
  4223. }
  4224. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4225. return this._worldMatrix;
  4226. };
  4227. return DirectionalLight;
  4228. })(BABYLON.Light);
  4229. BABYLON.DirectionalLight = DirectionalLight;
  4230. })(BABYLON || (BABYLON = {}));
  4231. var BABYLON;
  4232. (function (BABYLON) {
  4233. var ShadowGenerator = (function () {
  4234. function ShadowGenerator(mapSize, light) {
  4235. var _this = this;
  4236. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4237. this._darkness = 0;
  4238. this._transparencyShadow = false;
  4239. this._viewMatrix = BABYLON.Matrix.Zero();
  4240. this._projectionMatrix = BABYLON.Matrix.Zero();
  4241. this._transformMatrix = BABYLON.Matrix.Zero();
  4242. this._worldViewProjection = BABYLON.Matrix.Zero();
  4243. this._light = light;
  4244. this._scene = light.getScene();
  4245. light._shadowGenerator = this;
  4246. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4247. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4248. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4249. this._shadowMap.renderParticles = false;
  4250. var renderSubMesh = function (subMesh) {
  4251. var mesh = subMesh.getRenderingMesh();
  4252. var scene = _this._scene;
  4253. var engine = scene.getEngine();
  4254. engine.setState(subMesh.getMaterial().backFaceCulling);
  4255. var batch = mesh._getInstancesRenderList(subMesh._id);
  4256. if (batch.mustReturn) {
  4257. return;
  4258. }
  4259. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4260. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4261. engine.enableEffect(_this._effect);
  4262. mesh._bind(subMesh, _this._effect, false);
  4263. var material = subMesh.getMaterial();
  4264. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4265. if (material && material.needAlphaTesting()) {
  4266. var alphaTexture = material.getAlphaTestTexture();
  4267. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4268. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4269. }
  4270. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4271. if (useBones) {
  4272. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4273. }
  4274. if (hardwareInstancedRendering) {
  4275. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4276. } else {
  4277. if (batch.renderSelf[subMesh._id]) {
  4278. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4279. mesh._draw(subMesh, true);
  4280. }
  4281. if (batch.visibleInstances[subMesh._id]) {
  4282. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4283. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4284. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4285. mesh._draw(subMesh, true);
  4286. }
  4287. }
  4288. }
  4289. } else {
  4290. _this._shadowMap.resetRefreshCounter();
  4291. }
  4292. };
  4293. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4294. var index;
  4295. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4296. renderSubMesh(opaqueSubMeshes.data[index]);
  4297. }
  4298. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4299. renderSubMesh(alphaTestSubMeshes.data[index]);
  4300. }
  4301. if (_this._transparencyShadow) {
  4302. for (index = 0; index < transparentSubMeshes.length; index++) {
  4303. renderSubMesh(transparentSubMeshes.data[index]);
  4304. }
  4305. }
  4306. };
  4307. }
  4308. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4309. get: function () {
  4310. return ShadowGenerator._FILTER_NONE;
  4311. },
  4312. enumerable: true,
  4313. configurable: true
  4314. });
  4315. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4316. get: function () {
  4317. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4318. },
  4319. enumerable: true,
  4320. configurable: true
  4321. });
  4322. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4323. get: function () {
  4324. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4325. },
  4326. enumerable: true,
  4327. configurable: true
  4328. });
  4329. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4330. get: function () {
  4331. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4332. },
  4333. set: function (value) {
  4334. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4335. },
  4336. enumerable: true,
  4337. configurable: true
  4338. });
  4339. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4340. get: function () {
  4341. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4342. },
  4343. set: function (value) {
  4344. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4345. },
  4346. enumerable: true,
  4347. configurable: true
  4348. });
  4349. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4350. var defines = [];
  4351. if (this.useVarianceShadowMap) {
  4352. defines.push("#define VSM");
  4353. }
  4354. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4355. var mesh = subMesh.getMesh();
  4356. var material = subMesh.getMaterial();
  4357. if (material && material.needAlphaTesting()) {
  4358. defines.push("#define ALPHATEST");
  4359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4360. attribs.push(BABYLON.VertexBuffer.UVKind);
  4361. defines.push("#define UV1");
  4362. }
  4363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4365. defines.push("#define UV2");
  4366. }
  4367. }
  4368. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4371. defines.push("#define BONES");
  4372. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4373. }
  4374. if (useInstances) {
  4375. defines.push("#define INSTANCES");
  4376. attribs.push("world0");
  4377. attribs.push("world1");
  4378. attribs.push("world2");
  4379. attribs.push("world3");
  4380. }
  4381. var join = defines.join("\n");
  4382. if (this._cachedDefines != join) {
  4383. this._cachedDefines = join;
  4384. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4385. }
  4386. return this._effect.isReady();
  4387. };
  4388. ShadowGenerator.prototype.getShadowMap = function () {
  4389. return this._shadowMap;
  4390. };
  4391. ShadowGenerator.prototype.getLight = function () {
  4392. return this._light;
  4393. };
  4394. ShadowGenerator.prototype.getTransformMatrix = function () {
  4395. var lightPosition = this._light.position;
  4396. var lightDirection = this._light.direction;
  4397. if (this._light._computeTransformedPosition()) {
  4398. lightPosition = this._light._transformedPosition;
  4399. }
  4400. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4401. this._cachedPosition = lightPosition.clone();
  4402. this._cachedDirection = lightDirection.clone();
  4403. var activeCamera = this._scene.activeCamera;
  4404. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4405. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4406. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4407. }
  4408. return this._transformMatrix;
  4409. };
  4410. ShadowGenerator.prototype.getDarkness = function () {
  4411. return this._darkness;
  4412. };
  4413. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4414. if (darkness >= 1.0)
  4415. this._darkness = 1.0;
  4416. else if (darkness <= 0.0)
  4417. this._darkness = 0.0;
  4418. else
  4419. this._darkness = darkness;
  4420. };
  4421. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4422. this._transparencyShadow = hasShadow;
  4423. };
  4424. ShadowGenerator.prototype.dispose = function () {
  4425. this._shadowMap.dispose();
  4426. };
  4427. ShadowGenerator._FILTER_NONE = 0;
  4428. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4429. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4430. return ShadowGenerator;
  4431. })();
  4432. BABYLON.ShadowGenerator = ShadowGenerator;
  4433. })(BABYLON || (BABYLON = {}));
  4434. var __extends = this.__extends || function (d, b) {
  4435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4436. function __() { this.constructor = d; }
  4437. __.prototype = b.prototype;
  4438. d.prototype = new __();
  4439. };
  4440. var BABYLON;
  4441. (function (BABYLON) {
  4442. var HemisphericLight = (function (_super) {
  4443. __extends(HemisphericLight, _super);
  4444. function HemisphericLight(name, direction, scene) {
  4445. _super.call(this, name, scene);
  4446. this.direction = direction;
  4447. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4448. }
  4449. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4450. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4451. return this.direction;
  4452. };
  4453. HemisphericLight.prototype.getShadowGenerator = function () {
  4454. return null;
  4455. };
  4456. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4457. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4458. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4459. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4460. };
  4461. HemisphericLight.prototype._getWorldMatrix = function () {
  4462. if (!this._worldMatrix) {
  4463. this._worldMatrix = BABYLON.Matrix.Identity();
  4464. }
  4465. return this._worldMatrix;
  4466. };
  4467. return HemisphericLight;
  4468. })(BABYLON.Light);
  4469. BABYLON.HemisphericLight = HemisphericLight;
  4470. })(BABYLON || (BABYLON = {}));
  4471. var BABYLON;
  4472. (function (BABYLON) {
  4473. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4474. if (boxMin.x > sphereCenter.x + sphereRadius)
  4475. return false;
  4476. if (sphereCenter.x - sphereRadius > boxMax.x)
  4477. return false;
  4478. if (boxMin.y > sphereCenter.y + sphereRadius)
  4479. return false;
  4480. if (sphereCenter.y - sphereRadius > boxMax.y)
  4481. return false;
  4482. if (boxMin.z > sphereCenter.z + sphereRadius)
  4483. return false;
  4484. if (sphereCenter.z - sphereRadius > boxMax.z)
  4485. return false;
  4486. return true;
  4487. };
  4488. var getLowestRoot = function (a, b, c, maxR) {
  4489. var determinant = b * b - 4.0 * a * c;
  4490. var result = { root: 0, found: false };
  4491. if (determinant < 0)
  4492. return result;
  4493. var sqrtD = Math.sqrt(determinant);
  4494. var r1 = (-b - sqrtD) / (2.0 * a);
  4495. var r2 = (-b + sqrtD) / (2.0 * a);
  4496. if (r1 > r2) {
  4497. var temp = r2;
  4498. r2 = r1;
  4499. r1 = temp;
  4500. }
  4501. if (r1 > 0 && r1 < maxR) {
  4502. result.root = r1;
  4503. result.found = true;
  4504. return result;
  4505. }
  4506. if (r2 > 0 && r2 < maxR) {
  4507. result.root = r2;
  4508. result.found = true;
  4509. return result;
  4510. }
  4511. return result;
  4512. };
  4513. var Collider = (function () {
  4514. function Collider() {
  4515. this.radius = new BABYLON.Vector3(1, 1, 1);
  4516. this.retry = 0;
  4517. this.basePointWorld = BABYLON.Vector3.Zero();
  4518. this.velocityWorld = BABYLON.Vector3.Zero();
  4519. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4520. this._collisionPoint = BABYLON.Vector3.Zero();
  4521. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4522. this._tempVector = BABYLON.Vector3.Zero();
  4523. this._tempVector2 = BABYLON.Vector3.Zero();
  4524. this._tempVector3 = BABYLON.Vector3.Zero();
  4525. this._tempVector4 = BABYLON.Vector3.Zero();
  4526. this._edge = BABYLON.Vector3.Zero();
  4527. this._baseToVertex = BABYLON.Vector3.Zero();
  4528. this._destinationPoint = BABYLON.Vector3.Zero();
  4529. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4530. this._displacementVector = BABYLON.Vector3.Zero();
  4531. }
  4532. Collider.prototype._initialize = function (source, dir, e) {
  4533. this.velocity = dir;
  4534. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4535. this.basePoint = source;
  4536. source.multiplyToRef(this.radius, this.basePointWorld);
  4537. dir.multiplyToRef(this.radius, this.velocityWorld);
  4538. this.velocityWorldLength = this.velocityWorld.length();
  4539. this.epsilon = e;
  4540. this.collisionFound = false;
  4541. };
  4542. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4543. pa.subtractToRef(point, this._tempVector);
  4544. pb.subtractToRef(point, this._tempVector2);
  4545. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4546. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4547. if (d < 0)
  4548. return false;
  4549. pc.subtractToRef(point, this._tempVector3);
  4550. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4551. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4552. if (d < 0)
  4553. return false;
  4554. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4555. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4556. return d >= 0;
  4557. };
  4558. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4559. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4560. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4561. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4562. return false;
  4563. }
  4564. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4565. return false;
  4566. return true;
  4567. };
  4568. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4569. var t0;
  4570. var embeddedInPlane = false;
  4571. if (!subMesh._trianglePlanes) {
  4572. subMesh._trianglePlanes = [];
  4573. }
  4574. if (!subMesh._trianglePlanes[faceIndex]) {
  4575. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4576. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4577. }
  4578. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4579. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4580. return;
  4581. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4582. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4583. if (normalDotVelocity == 0) {
  4584. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4585. return;
  4586. embeddedInPlane = true;
  4587. t0 = 0;
  4588. } else {
  4589. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4590. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4591. if (t0 > t1) {
  4592. var temp = t1;
  4593. t1 = t0;
  4594. t0 = temp;
  4595. }
  4596. if (t0 > 1.0 || t1 < 0.0)
  4597. return;
  4598. if (t0 < 0)
  4599. t0 = 0;
  4600. if (t0 > 1.0)
  4601. t0 = 1.0;
  4602. }
  4603. this._collisionPoint.copyFromFloats(0, 0, 0);
  4604. var found = false;
  4605. var t = 1.0;
  4606. if (!embeddedInPlane) {
  4607. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4608. this.velocity.scaleToRef(t0, this._tempVector);
  4609. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4610. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4611. found = true;
  4612. t = t0;
  4613. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4614. }
  4615. }
  4616. if (!found) {
  4617. var velocitySquaredLength = this.velocity.lengthSquared();
  4618. var a = velocitySquaredLength;
  4619. this.basePoint.subtractToRef(p1, this._tempVector);
  4620. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4621. var c = this._tempVector.lengthSquared() - 1.0;
  4622. var lowestRoot = getLowestRoot(a, b, c, t);
  4623. if (lowestRoot.found) {
  4624. t = lowestRoot.root;
  4625. found = true;
  4626. this._collisionPoint.copyFrom(p1);
  4627. }
  4628. this.basePoint.subtractToRef(p2, this._tempVector);
  4629. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4630. c = this._tempVector.lengthSquared() - 1.0;
  4631. lowestRoot = getLowestRoot(a, b, c, t);
  4632. if (lowestRoot.found) {
  4633. t = lowestRoot.root;
  4634. found = true;
  4635. this._collisionPoint.copyFrom(p2);
  4636. }
  4637. this.basePoint.subtractToRef(p3, this._tempVector);
  4638. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4639. c = this._tempVector.lengthSquared() - 1.0;
  4640. lowestRoot = getLowestRoot(a, b, c, t);
  4641. if (lowestRoot.found) {
  4642. t = lowestRoot.root;
  4643. found = true;
  4644. this._collisionPoint.copyFrom(p3);
  4645. }
  4646. p2.subtractToRef(p1, this._edge);
  4647. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4648. var edgeSquaredLength = this._edge.lengthSquared();
  4649. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4650. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4651. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4652. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4653. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4654. lowestRoot = getLowestRoot(a, b, c, t);
  4655. if (lowestRoot.found) {
  4656. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4657. if (f >= 0.0 && f <= 1.0) {
  4658. t = lowestRoot.root;
  4659. found = true;
  4660. this._edge.scaleInPlace(f);
  4661. p1.addToRef(this._edge, this._collisionPoint);
  4662. }
  4663. }
  4664. p3.subtractToRef(p2, this._edge);
  4665. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4666. edgeSquaredLength = this._edge.lengthSquared();
  4667. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4668. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4669. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4670. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4671. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4672. lowestRoot = getLowestRoot(a, b, c, t);
  4673. if (lowestRoot.found) {
  4674. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4675. if (f >= 0.0 && f <= 1.0) {
  4676. t = lowestRoot.root;
  4677. found = true;
  4678. this._edge.scaleInPlace(f);
  4679. p2.addToRef(this._edge, this._collisionPoint);
  4680. }
  4681. }
  4682. p1.subtractToRef(p3, this._edge);
  4683. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4684. edgeSquaredLength = this._edge.lengthSquared();
  4685. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4686. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4687. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4688. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4689. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4690. lowestRoot = getLowestRoot(a, b, c, t);
  4691. if (lowestRoot.found) {
  4692. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4693. if (f >= 0.0 && f <= 1.0) {
  4694. t = lowestRoot.root;
  4695. found = true;
  4696. this._edge.scaleInPlace(f);
  4697. p3.addToRef(this._edge, this._collisionPoint);
  4698. }
  4699. }
  4700. }
  4701. if (found) {
  4702. var distToCollision = t * this.velocity.length();
  4703. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4704. if (!this.intersectionPoint) {
  4705. this.intersectionPoint = this._collisionPoint.clone();
  4706. } else {
  4707. this.intersectionPoint.copyFrom(this._collisionPoint);
  4708. }
  4709. this.nearestDistance = distToCollision;
  4710. this.collisionFound = true;
  4711. this.collidedMesh = subMesh.getMesh();
  4712. }
  4713. }
  4714. };
  4715. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4716. for (var i = indexStart; i < indexEnd; i += 3) {
  4717. var p1 = pts[indices[i] - decal];
  4718. var p2 = pts[indices[i + 1] - decal];
  4719. var p3 = pts[indices[i + 2] - decal];
  4720. this._testTriangle(i, subMesh, p3, p2, p1);
  4721. }
  4722. };
  4723. Collider.prototype._getResponse = function (pos, vel) {
  4724. pos.addToRef(vel, this._destinationPoint);
  4725. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4726. this.basePoint.addToRef(vel, pos);
  4727. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4728. this._slidePlaneNormal.normalize();
  4729. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4730. pos.addInPlace(this._displacementVector);
  4731. this.intersectionPoint.addInPlace(this._displacementVector);
  4732. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4733. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4734. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4735. };
  4736. return Collider;
  4737. })();
  4738. BABYLON.Collider = Collider;
  4739. })(BABYLON || (BABYLON = {}));
  4740. var __extends = this.__extends || function (d, b) {
  4741. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4742. function __() { this.constructor = d; }
  4743. __.prototype = b.prototype;
  4744. d.prototype = new __();
  4745. };
  4746. var BABYLON;
  4747. (function (BABYLON) {
  4748. var Camera = (function (_super) {
  4749. __extends(Camera, _super);
  4750. function Camera(name, position, scene) {
  4751. _super.call(this, name, scene);
  4752. this.position = position;
  4753. this.upVector = BABYLON.Vector3.Up();
  4754. this.orthoLeft = null;
  4755. this.orthoRight = null;
  4756. this.orthoBottom = null;
  4757. this.orthoTop = null;
  4758. this.fov = 0.8;
  4759. this.minZ = 1.0;
  4760. this.maxZ = 10000.0;
  4761. this.inertia = 0.9;
  4762. this.mode = Camera.PERSPECTIVE_CAMERA;
  4763. this.isIntermediate = false;
  4764. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4765. this.subCameras = [];
  4766. this.layerMask = 0xFFFFFFFF;
  4767. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4768. this._projectionMatrix = new BABYLON.Matrix();
  4769. this._postProcesses = new Array();
  4770. this._postProcessesTakenIndices = [];
  4771. scene.cameras.push(this);
  4772. if (!scene.activeCamera) {
  4773. scene.activeCamera = this;
  4774. }
  4775. }
  4776. Camera.prototype._initCache = function () {
  4777. _super.prototype._initCache.call(this);
  4778. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4779. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4780. this._cache.mode = undefined;
  4781. this._cache.minZ = undefined;
  4782. this._cache.maxZ = undefined;
  4783. this._cache.fov = undefined;
  4784. this._cache.aspectRatio = undefined;
  4785. this._cache.orthoLeft = undefined;
  4786. this._cache.orthoRight = undefined;
  4787. this._cache.orthoBottom = undefined;
  4788. this._cache.orthoTop = undefined;
  4789. this._cache.renderWidth = undefined;
  4790. this._cache.renderHeight = undefined;
  4791. };
  4792. Camera.prototype._updateCache = function (ignoreParentClass) {
  4793. if (!ignoreParentClass) {
  4794. _super.prototype._updateCache.call(this);
  4795. }
  4796. var engine = this.getEngine();
  4797. this._cache.position.copyFrom(this.position);
  4798. this._cache.upVector.copyFrom(this.upVector);
  4799. this._cache.mode = this.mode;
  4800. this._cache.minZ = this.minZ;
  4801. this._cache.maxZ = this.maxZ;
  4802. this._cache.fov = this.fov;
  4803. this._cache.aspectRatio = engine.getAspectRatio(this);
  4804. this._cache.orthoLeft = this.orthoLeft;
  4805. this._cache.orthoRight = this.orthoRight;
  4806. this._cache.orthoBottom = this.orthoBottom;
  4807. this._cache.orthoTop = this.orthoTop;
  4808. this._cache.renderWidth = engine.getRenderWidth();
  4809. this._cache.renderHeight = engine.getRenderHeight();
  4810. };
  4811. Camera.prototype._updateFromScene = function () {
  4812. this.updateCache();
  4813. this._update();
  4814. };
  4815. Camera.prototype._isSynchronized = function () {
  4816. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4817. };
  4818. Camera.prototype._isSynchronizedViewMatrix = function () {
  4819. if (!_super.prototype._isSynchronized.call(this))
  4820. return false;
  4821. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4822. };
  4823. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4824. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4825. if (!check) {
  4826. return false;
  4827. }
  4828. var engine = this.getEngine();
  4829. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4830. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4831. } else {
  4832. 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();
  4833. }
  4834. return check;
  4835. };
  4836. Camera.prototype.attachControl = function (element) {
  4837. };
  4838. Camera.prototype.detachControl = function (element) {
  4839. };
  4840. Camera.prototype._update = function () {
  4841. };
  4842. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4843. if (typeof insertAt === "undefined") { insertAt = null; }
  4844. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4845. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4846. return 0;
  4847. }
  4848. if (insertAt == null || insertAt < 0) {
  4849. this._postProcesses.push(postProcess);
  4850. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4851. return this._postProcesses.length - 1;
  4852. }
  4853. var add = 0;
  4854. if (this._postProcesses[insertAt]) {
  4855. var start = this._postProcesses.length - 1;
  4856. for (var i = start; i >= insertAt + 1; --i) {
  4857. this._postProcesses[i + 1] = this._postProcesses[i];
  4858. }
  4859. add = 1;
  4860. }
  4861. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4862. if (this._postProcessesTakenIndices[i] < insertAt) {
  4863. continue;
  4864. }
  4865. start = this._postProcessesTakenIndices.length - 1;
  4866. for (var j = start; j >= i; --j) {
  4867. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4868. }
  4869. this._postProcessesTakenIndices[i] = insertAt;
  4870. break;
  4871. }
  4872. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4873. this._postProcessesTakenIndices.push(insertAt);
  4874. }
  4875. var result = insertAt + add;
  4876. this._postProcesses[result] = postProcess;
  4877. return result;
  4878. };
  4879. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4880. if (typeof atIndices === "undefined") { atIndices = null; }
  4881. var result = [];
  4882. if (!atIndices) {
  4883. var length = this._postProcesses.length;
  4884. for (var i = 0; i < length; i++) {
  4885. if (this._postProcesses[i] !== postProcess) {
  4886. continue;
  4887. }
  4888. delete this._postProcesses[i];
  4889. var index = this._postProcessesTakenIndices.indexOf(i);
  4890. this._postProcessesTakenIndices.splice(index, 1);
  4891. }
  4892. } else {
  4893. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4894. for (i = 0; i < atIndices.length; i++) {
  4895. var foundPostProcess = this._postProcesses[atIndices[i]];
  4896. if (foundPostProcess !== postProcess) {
  4897. result.push(i);
  4898. continue;
  4899. }
  4900. delete this._postProcesses[atIndices[i]];
  4901. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4902. this._postProcessesTakenIndices.splice(index, 1);
  4903. }
  4904. }
  4905. return result;
  4906. };
  4907. Camera.prototype.getWorldMatrix = function () {
  4908. if (!this._worldMatrix) {
  4909. this._worldMatrix = BABYLON.Matrix.Identity();
  4910. }
  4911. var viewMatrix = this.getViewMatrix();
  4912. viewMatrix.invertToRef(this._worldMatrix);
  4913. return this._worldMatrix;
  4914. };
  4915. Camera.prototype._getViewMatrix = function () {
  4916. return BABYLON.Matrix.Identity();
  4917. };
  4918. Camera.prototype.getViewMatrix = function () {
  4919. this._computedViewMatrix = this._computeViewMatrix();
  4920. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4921. return this._computedViewMatrix;
  4922. }
  4923. if (!this._worldMatrix) {
  4924. this._worldMatrix = BABYLON.Matrix.Identity();
  4925. }
  4926. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4927. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4928. this._computedViewMatrix.invert();
  4929. this._currentRenderId = this.getScene().getRenderId();
  4930. return this._computedViewMatrix;
  4931. };
  4932. Camera.prototype._computeViewMatrix = function (force) {
  4933. if (!force && this._isSynchronizedViewMatrix()) {
  4934. return this._computedViewMatrix;
  4935. }
  4936. this._computedViewMatrix = this._getViewMatrix();
  4937. if (!this.parent || !this.parent.getWorldMatrix) {
  4938. this._currentRenderId = this.getScene().getRenderId();
  4939. }
  4940. return this._computedViewMatrix;
  4941. };
  4942. Camera.prototype.getProjectionMatrix = function (force) {
  4943. if (!force && this._isSynchronizedProjectionMatrix()) {
  4944. return this._projectionMatrix;
  4945. }
  4946. var engine = this.getEngine();
  4947. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4948. if (this.minZ <= 0) {
  4949. this.minZ = 0.1;
  4950. }
  4951. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4952. return this._projectionMatrix;
  4953. }
  4954. var halfWidth = engine.getRenderWidth() / 2.0;
  4955. var halfHeight = engine.getRenderHeight() / 2.0;
  4956. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4957. return this._projectionMatrix;
  4958. };
  4959. Camera.prototype.dispose = function () {
  4960. var index = this.getScene().cameras.indexOf(this);
  4961. this.getScene().cameras.splice(index, 1);
  4962. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4963. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4964. }
  4965. };
  4966. Camera.PERSPECTIVE_CAMERA = 0;
  4967. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4968. return Camera;
  4969. })(BABYLON.Node);
  4970. BABYLON.Camera = Camera;
  4971. })(BABYLON || (BABYLON = {}));
  4972. var __extends = this.__extends || function (d, b) {
  4973. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4974. function __() { this.constructor = d; }
  4975. __.prototype = b.prototype;
  4976. d.prototype = new __();
  4977. };
  4978. var BABYLON;
  4979. (function (BABYLON) {
  4980. var TargetCamera = (function (_super) {
  4981. __extends(TargetCamera, _super);
  4982. function TargetCamera(name, position, scene) {
  4983. _super.call(this, name, position, scene);
  4984. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4985. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4986. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4987. this.speed = 2.0;
  4988. this.noRotationConstraint = false;
  4989. this.lockedTarget = null;
  4990. this._currentTarget = BABYLON.Vector3.Zero();
  4991. this._viewMatrix = BABYLON.Matrix.Zero();
  4992. this._camMatrix = BABYLON.Matrix.Zero();
  4993. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4994. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4995. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4996. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4997. this._lookAtTemp = BABYLON.Matrix.Zero();
  4998. this._tempMatrix = BABYLON.Matrix.Zero();
  4999. }
  5000. TargetCamera.prototype._getLockedTargetPosition = function () {
  5001. if (!this.lockedTarget) {
  5002. return null;
  5003. }
  5004. return this.lockedTarget.position || this.lockedTarget;
  5005. };
  5006. TargetCamera.prototype._initCache = function () {
  5007. _super.prototype._initCache.call(this);
  5008. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5009. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5010. };
  5011. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5012. if (!ignoreParentClass) {
  5013. _super.prototype._updateCache.call(this);
  5014. }
  5015. var lockedTargetPosition = this._getLockedTargetPosition();
  5016. if (!lockedTargetPosition) {
  5017. this._cache.lockedTarget = null;
  5018. } else {
  5019. if (!this._cache.lockedTarget) {
  5020. this._cache.lockedTarget = lockedTargetPosition.clone();
  5021. } else {
  5022. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5023. }
  5024. }
  5025. this._cache.rotation.copyFrom(this.rotation);
  5026. };
  5027. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5028. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5029. return false;
  5030. }
  5031. var lockedTargetPosition = this._getLockedTargetPosition();
  5032. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5033. };
  5034. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5035. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5036. };
  5037. TargetCamera.prototype.setTarget = function (target) {
  5038. this.upVector.normalize();
  5039. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5040. this._camMatrix.invert();
  5041. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5042. var vDir = target.subtract(this.position);
  5043. if (vDir.x >= 0.0) {
  5044. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5045. } else {
  5046. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5047. }
  5048. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5049. if (isNaN(this.rotation.x)) {
  5050. this.rotation.x = 0;
  5051. }
  5052. if (isNaN(this.rotation.y)) {
  5053. this.rotation.y = 0;
  5054. }
  5055. if (isNaN(this.rotation.z)) {
  5056. this.rotation.z = 0;
  5057. }
  5058. };
  5059. TargetCamera.prototype.getTarget = function () {
  5060. return this._currentTarget;
  5061. };
  5062. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5063. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5064. };
  5065. TargetCamera.prototype._updatePosition = function () {
  5066. this.position.addInPlace(this.cameraDirection);
  5067. };
  5068. TargetCamera.prototype._update = function () {
  5069. var needToMove = this._decideIfNeedsToMove();
  5070. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5071. if (needToMove) {
  5072. this._updatePosition();
  5073. }
  5074. if (needToRotate) {
  5075. this.rotation.x += this.cameraRotation.x;
  5076. this.rotation.y += this.cameraRotation.y;
  5077. if (!this.noRotationConstraint) {
  5078. var limit = (Math.PI / 2) * 0.95;
  5079. if (this.rotation.x > limit)
  5080. this.rotation.x = limit;
  5081. if (this.rotation.x < -limit)
  5082. this.rotation.x = -limit;
  5083. }
  5084. }
  5085. if (needToMove) {
  5086. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5087. this.cameraDirection.x = 0;
  5088. }
  5089. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5090. this.cameraDirection.y = 0;
  5091. }
  5092. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5093. this.cameraDirection.z = 0;
  5094. }
  5095. this.cameraDirection.scaleInPlace(this.inertia);
  5096. }
  5097. if (needToRotate) {
  5098. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5099. this.cameraRotation.x = 0;
  5100. }
  5101. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5102. this.cameraRotation.y = 0;
  5103. }
  5104. this.cameraRotation.scaleInPlace(this.inertia);
  5105. }
  5106. };
  5107. TargetCamera.prototype._getViewMatrix = function () {
  5108. if (!this.lockedTarget) {
  5109. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5110. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5111. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5112. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5113. this._lookAtTemp.invert();
  5114. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5115. } else {
  5116. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5117. }
  5118. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5119. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5120. } else {
  5121. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5122. }
  5123. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5124. return this._viewMatrix;
  5125. };
  5126. return TargetCamera;
  5127. })(BABYLON.Camera);
  5128. BABYLON.TargetCamera = TargetCamera;
  5129. })(BABYLON || (BABYLON = {}));
  5130. var __extends = this.__extends || function (d, b) {
  5131. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5132. function __() { this.constructor = d; }
  5133. __.prototype = b.prototype;
  5134. d.prototype = new __();
  5135. };
  5136. var BABYLON;
  5137. (function (BABYLON) {
  5138. var FollowCamera = (function (_super) {
  5139. __extends(FollowCamera, _super);
  5140. function FollowCamera(name, position, scene) {
  5141. _super.call(this, name, position, scene);
  5142. this.radius = 12;
  5143. this.rotationOffset = 0;
  5144. this.heightOffset = 4;
  5145. this.cameraAcceleration = 0.05;
  5146. this.maxCameraSpeed = 20;
  5147. }
  5148. FollowCamera.prototype.getRadians = function (degrees) {
  5149. return degrees * Math.PI / 180;
  5150. };
  5151. FollowCamera.prototype.follow = function (cameraTarget) {
  5152. if (!cameraTarget)
  5153. return;
  5154. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5155. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5156. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5157. var dx = targetX - this.position.x;
  5158. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5159. var dz = (targetZ) - this.position.z;
  5160. var vx = dx * this.cameraAcceleration * 2;
  5161. var vy = dy * this.cameraAcceleration;
  5162. var vz = dz * this.cameraAcceleration * 2;
  5163. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5164. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5165. }
  5166. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5167. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5168. }
  5169. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5170. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5171. }
  5172. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5173. this.setTarget(cameraTarget.position);
  5174. };
  5175. FollowCamera.prototype._update = function () {
  5176. _super.prototype._update.call(this);
  5177. this.follow(this.target);
  5178. };
  5179. return FollowCamera;
  5180. })(BABYLON.TargetCamera);
  5181. BABYLON.FollowCamera = FollowCamera;
  5182. })(BABYLON || (BABYLON = {}));
  5183. var __extends = this.__extends || function (d, b) {
  5184. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5185. function __() { this.constructor = d; }
  5186. __.prototype = b.prototype;
  5187. d.prototype = new __();
  5188. };
  5189. var BABYLON;
  5190. (function (BABYLON) {
  5191. var FreeCamera = (function (_super) {
  5192. __extends(FreeCamera, _super);
  5193. function FreeCamera(name, position, scene) {
  5194. _super.call(this, name, position, scene);
  5195. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5196. this.keysUp = [38];
  5197. this.keysDown = [40];
  5198. this.keysLeft = [37];
  5199. this.keysRight = [39];
  5200. this.checkCollisions = false;
  5201. this.applyGravity = false;
  5202. this.angularSensibility = 2000.0;
  5203. this._keys = [];
  5204. this._collider = new BABYLON.Collider();
  5205. this._needMoveForGravity = true;
  5206. this._oldPosition = BABYLON.Vector3.Zero();
  5207. this._diffPosition = BABYLON.Vector3.Zero();
  5208. this._newPosition = BABYLON.Vector3.Zero();
  5209. }
  5210. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5211. var _this = this;
  5212. var previousPosition;
  5213. var engine = this.getEngine();
  5214. if (this._attachedElement) {
  5215. return;
  5216. }
  5217. this._attachedElement = element;
  5218. if (this._onMouseDown === undefined) {
  5219. this._onMouseDown = function (evt) {
  5220. previousPosition = {
  5221. x: evt.clientX,
  5222. y: evt.clientY
  5223. };
  5224. if (!noPreventDefault) {
  5225. evt.preventDefault();
  5226. }
  5227. };
  5228. this._onMouseUp = function (evt) {
  5229. previousPosition = null;
  5230. if (!noPreventDefault) {
  5231. evt.preventDefault();
  5232. }
  5233. };
  5234. this._onMouseOut = function (evt) {
  5235. previousPosition = null;
  5236. _this._keys = [];
  5237. if (!noPreventDefault) {
  5238. evt.preventDefault();
  5239. }
  5240. };
  5241. this._onMouseMove = function (evt) {
  5242. if (!previousPosition && !engine.isPointerLock) {
  5243. return;
  5244. }
  5245. var offsetX;
  5246. var offsetY;
  5247. if (!engine.isPointerLock) {
  5248. offsetX = evt.clientX - previousPosition.x;
  5249. offsetY = evt.clientY - previousPosition.y;
  5250. } else {
  5251. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5252. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5253. }
  5254. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5255. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5256. previousPosition = {
  5257. x: evt.clientX,
  5258. y: evt.clientY
  5259. };
  5260. if (!noPreventDefault) {
  5261. evt.preventDefault();
  5262. }
  5263. };
  5264. this._onKeyDown = function (evt) {
  5265. 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) {
  5266. var index = _this._keys.indexOf(evt.keyCode);
  5267. if (index === -1) {
  5268. _this._keys.push(evt.keyCode);
  5269. }
  5270. if (!noPreventDefault) {
  5271. evt.preventDefault();
  5272. }
  5273. }
  5274. };
  5275. this._onKeyUp = function (evt) {
  5276. 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) {
  5277. var index = _this._keys.indexOf(evt.keyCode);
  5278. if (index >= 0) {
  5279. _this._keys.splice(index, 1);
  5280. }
  5281. if (!noPreventDefault) {
  5282. evt.preventDefault();
  5283. }
  5284. }
  5285. };
  5286. this._onLostFocus = function () {
  5287. _this._keys = [];
  5288. };
  5289. this._reset = function () {
  5290. _this._keys = [];
  5291. previousPosition = null;
  5292. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5293. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5294. };
  5295. }
  5296. element.addEventListener("mousedown", this._onMouseDown, false);
  5297. element.addEventListener("mouseup", this._onMouseUp, false);
  5298. element.addEventListener("mouseout", this._onMouseOut, false);
  5299. element.addEventListener("mousemove", this._onMouseMove, false);
  5300. BABYLON.Tools.RegisterTopRootEvents([
  5301. { name: "keydown", handler: this._onKeyDown },
  5302. { name: "keyup", handler: this._onKeyUp },
  5303. { name: "blur", handler: this._onLostFocus }
  5304. ]);
  5305. };
  5306. FreeCamera.prototype.detachControl = function (element) {
  5307. if (this._attachedElement != element) {
  5308. return;
  5309. }
  5310. element.removeEventListener("mousedown", this._onMouseDown);
  5311. element.removeEventListener("mouseup", this._onMouseUp);
  5312. element.removeEventListener("mouseout", this._onMouseOut);
  5313. element.removeEventListener("mousemove", this._onMouseMove);
  5314. BABYLON.Tools.UnregisterTopRootEvents([
  5315. { name: "keydown", handler: this._onKeyDown },
  5316. { name: "keyup", handler: this._onKeyUp },
  5317. { name: "blur", handler: this._onLostFocus }
  5318. ]);
  5319. this._attachedElement = null;
  5320. if (this._reset) {
  5321. this._reset();
  5322. }
  5323. };
  5324. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5325. var globalPosition;
  5326. if (this.parent) {
  5327. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5328. } else {
  5329. globalPosition = this.position;
  5330. }
  5331. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5332. this._collider.radius = this.ellipsoid;
  5333. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5334. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5335. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5336. this.position.addInPlace(this._diffPosition);
  5337. if (this.onCollide) {
  5338. this.onCollide(this._collider.collidedMesh);
  5339. }
  5340. }
  5341. };
  5342. FreeCamera.prototype._checkInputs = function () {
  5343. if (!this._localDirection) {
  5344. this._localDirection = BABYLON.Vector3.Zero();
  5345. this._transformedDirection = BABYLON.Vector3.Zero();
  5346. }
  5347. for (var index = 0; index < this._keys.length; index++) {
  5348. var keyCode = this._keys[index];
  5349. var speed = this._computeLocalCameraSpeed();
  5350. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5351. this._localDirection.copyFromFloats(-speed, 0, 0);
  5352. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5353. this._localDirection.copyFromFloats(0, 0, speed);
  5354. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5355. this._localDirection.copyFromFloats(speed, 0, 0);
  5356. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5357. this._localDirection.copyFromFloats(0, 0, -speed);
  5358. }
  5359. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5360. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5361. this.cameraDirection.addInPlace(this._transformedDirection);
  5362. }
  5363. };
  5364. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5365. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5366. };
  5367. FreeCamera.prototype._updatePosition = function () {
  5368. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5369. this._collideWithWorld(this.cameraDirection);
  5370. if (this.applyGravity) {
  5371. var oldPosition = this.position;
  5372. this._collideWithWorld(this.getScene().gravity);
  5373. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5374. }
  5375. } else {
  5376. this.position.addInPlace(this.cameraDirection);
  5377. }
  5378. };
  5379. FreeCamera.prototype._update = function () {
  5380. this._checkInputs();
  5381. _super.prototype._update.call(this);
  5382. };
  5383. return FreeCamera;
  5384. })(BABYLON.TargetCamera);
  5385. BABYLON.FreeCamera = FreeCamera;
  5386. })(BABYLON || (BABYLON = {}));
  5387. var __extends = this.__extends || function (d, b) {
  5388. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5389. function __() { this.constructor = d; }
  5390. __.prototype = b.prototype;
  5391. d.prototype = new __();
  5392. };
  5393. var BABYLON;
  5394. (function (BABYLON) {
  5395. var TouchCamera = (function (_super) {
  5396. __extends(TouchCamera, _super);
  5397. function TouchCamera(name, position, scene) {
  5398. _super.call(this, name, position, scene);
  5399. this._offsetX = null;
  5400. this._offsetY = null;
  5401. this._pointerCount = 0;
  5402. this._pointerPressed = [];
  5403. this.angularSensibility = 200000.0;
  5404. this.moveSensibility = 500.0;
  5405. }
  5406. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5407. var _this = this;
  5408. var previousPosition;
  5409. if (this._attachedCanvas) {
  5410. return;
  5411. }
  5412. this._attachedCanvas = canvas;
  5413. if (this._onPointerDown === undefined) {
  5414. this._onPointerDown = function (evt) {
  5415. if (!noPreventDefault) {
  5416. evt.preventDefault();
  5417. }
  5418. _this._pointerPressed.push(evt.pointerId);
  5419. if (_this._pointerPressed.length !== 1) {
  5420. return;
  5421. }
  5422. previousPosition = {
  5423. x: evt.clientX,
  5424. y: evt.clientY
  5425. };
  5426. };
  5427. this._onPointerUp = function (evt) {
  5428. if (!noPreventDefault) {
  5429. evt.preventDefault();
  5430. }
  5431. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5432. if (index === -1) {
  5433. return;
  5434. }
  5435. _this._pointerPressed.splice(index, 1);
  5436. if (index != 0) {
  5437. return;
  5438. }
  5439. previousPosition = null;
  5440. _this._offsetX = null;
  5441. _this._offsetY = null;
  5442. };
  5443. this._onPointerMove = function (evt) {
  5444. if (!noPreventDefault) {
  5445. evt.preventDefault();
  5446. }
  5447. if (!previousPosition) {
  5448. return;
  5449. }
  5450. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5451. if (index != 0) {
  5452. return;
  5453. }
  5454. _this._offsetX = evt.clientX - previousPosition.x;
  5455. _this._offsetY = -(evt.clientY - previousPosition.y);
  5456. };
  5457. this._onLostFocus = function () {
  5458. _this._offsetX = null;
  5459. _this._offsetY = null;
  5460. };
  5461. }
  5462. canvas.addEventListener("pointerdown", this._onPointerDown);
  5463. canvas.addEventListener("pointerup", this._onPointerUp);
  5464. canvas.addEventListener("pointerout", this._onPointerUp);
  5465. canvas.addEventListener("pointermove", this._onPointerMove);
  5466. BABYLON.Tools.RegisterTopRootEvents([
  5467. { name: "blur", handler: this._onLostFocus }
  5468. ]);
  5469. };
  5470. TouchCamera.prototype.detachControl = function (canvas) {
  5471. if (this._attachedCanvas != canvas) {
  5472. return;
  5473. }
  5474. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5475. canvas.removeEventListener("pointerup", this._onPointerUp);
  5476. canvas.removeEventListener("pointerout", this._onPointerUp);
  5477. canvas.removeEventListener("pointermove", this._onPointerMove);
  5478. BABYLON.Tools.UnregisterTopRootEvents([
  5479. { name: "blur", handler: this._onLostFocus }
  5480. ]);
  5481. this._attachedCanvas = null;
  5482. };
  5483. TouchCamera.prototype._checkInputs = function () {
  5484. if (!this._offsetX) {
  5485. return;
  5486. }
  5487. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5488. if (this._pointerPressed.length > 1) {
  5489. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5490. } else {
  5491. var speed = this._computeLocalCameraSpeed();
  5492. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5493. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5494. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5495. }
  5496. };
  5497. return TouchCamera;
  5498. })(BABYLON.FreeCamera);
  5499. BABYLON.TouchCamera = TouchCamera;
  5500. })(BABYLON || (BABYLON = {}));
  5501. var __extends = this.__extends || function (d, b) {
  5502. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5503. function __() { this.constructor = d; }
  5504. __.prototype = b.prototype;
  5505. d.prototype = new __();
  5506. };
  5507. var BABYLON;
  5508. (function (BABYLON) {
  5509. var DeviceOrientationCamera = (function (_super) {
  5510. __extends(DeviceOrientationCamera, _super);
  5511. function DeviceOrientationCamera(name, position, scene) {
  5512. var _this = this;
  5513. _super.call(this, name, position, scene);
  5514. this._offsetX = null;
  5515. this._offsetY = null;
  5516. this._orientationGamma = 0;
  5517. this._orientationBeta = 0;
  5518. this._initialOrientationGamma = 0;
  5519. this._initialOrientationBeta = 0;
  5520. this.angularSensibility = 10000.0;
  5521. this.moveSensibility = 50.0;
  5522. window.addEventListener("resize", function () {
  5523. _this._initialOrientationGamma = null;
  5524. }, false);
  5525. }
  5526. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5527. var _this = this;
  5528. if (this._attachedCanvas) {
  5529. return;
  5530. }
  5531. this._attachedCanvas = canvas;
  5532. if (!this._orientationChanged) {
  5533. this._orientationChanged = function (evt) {
  5534. if (!_this._initialOrientationGamma) {
  5535. _this._initialOrientationGamma = evt.gamma;
  5536. _this._initialOrientationBeta = evt.beta;
  5537. }
  5538. _this._orientationGamma = evt.gamma;
  5539. _this._orientationBeta = evt.beta;
  5540. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5541. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5542. };
  5543. }
  5544. window.addEventListener("deviceorientation", this._orientationChanged);
  5545. };
  5546. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5547. if (this._attachedCanvas != canvas) {
  5548. return;
  5549. }
  5550. window.removeEventListener("deviceorientation", this._orientationChanged);
  5551. this._attachedCanvas = null;
  5552. this._orientationGamma = 0;
  5553. this._orientationBeta = 0;
  5554. this._initialOrientationGamma = 0;
  5555. this._initialOrientationBeta = 0;
  5556. };
  5557. DeviceOrientationCamera.prototype._checkInputs = function () {
  5558. if (!this._offsetX) {
  5559. return;
  5560. }
  5561. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5562. var speed = this._computeLocalCameraSpeed();
  5563. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5564. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5565. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5566. };
  5567. return DeviceOrientationCamera;
  5568. })(BABYLON.FreeCamera);
  5569. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5570. })(BABYLON || (BABYLON = {}));
  5571. var __extends = this.__extends || function (d, b) {
  5572. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5573. function __() { this.constructor = d; }
  5574. __.prototype = b.prototype;
  5575. d.prototype = new __();
  5576. };
  5577. var BABYLON;
  5578. (function (BABYLON) {
  5579. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5580. var ArcRotateCamera = (function (_super) {
  5581. __extends(ArcRotateCamera, _super);
  5582. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5583. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5584. this.alpha = alpha;
  5585. this.beta = beta;
  5586. this.radius = radius;
  5587. this.target = target;
  5588. this.inertialAlphaOffset = 0;
  5589. this.inertialBetaOffset = 0;
  5590. this.inertialRadiusOffset = 0;
  5591. this.lowerAlphaLimit = null;
  5592. this.upperAlphaLimit = null;
  5593. this.lowerBetaLimit = 0.01;
  5594. this.upperBetaLimit = Math.PI;
  5595. this.lowerRadiusLimit = null;
  5596. this.upperRadiusLimit = null;
  5597. this.angularSensibility = 1000.0;
  5598. this.wheelPrecision = 3.0;
  5599. this.keysUp = [38];
  5600. this.keysDown = [40];
  5601. this.keysLeft = [37];
  5602. this.keysRight = [39];
  5603. this.zoomOnFactor = 1;
  5604. this._keys = [];
  5605. this._viewMatrix = new BABYLON.Matrix();
  5606. this.checkCollisions = false;
  5607. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5608. this._collider = new BABYLON.Collider();
  5609. this._previousPosition = BABYLON.Vector3.Zero();
  5610. this._collisionVelocity = BABYLON.Vector3.Zero();
  5611. this._newPosition = BABYLON.Vector3.Zero();
  5612. this.pinchPrecision = 20;
  5613. this.getViewMatrix();
  5614. }
  5615. ArcRotateCamera.prototype._getTargetPosition = function () {
  5616. return this.target.position || this.target;
  5617. };
  5618. ArcRotateCamera.prototype._initCache = function () {
  5619. _super.prototype._initCache.call(this);
  5620. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5621. this._cache.alpha = undefined;
  5622. this._cache.beta = undefined;
  5623. this._cache.radius = undefined;
  5624. };
  5625. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5626. if (!ignoreParentClass) {
  5627. _super.prototype._updateCache.call(this);
  5628. }
  5629. this._cache.target.copyFrom(this._getTargetPosition());
  5630. this._cache.alpha = this.alpha;
  5631. this._cache.beta = this.beta;
  5632. this._cache.radius = this.radius;
  5633. };
  5634. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5635. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5636. return false;
  5637. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5638. };
  5639. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5640. var _this = this;
  5641. var previousPosition;
  5642. var pointerId;
  5643. var pinchStarted = false;
  5644. var pinchPointX1, pinchPointX2;
  5645. if (this._attachedElement) {
  5646. return;
  5647. }
  5648. this._attachedElement = element;
  5649. var engine = this.getEngine();
  5650. if (this._onPointerDown === undefined) {
  5651. this._onPointerDown = function (evt) {
  5652. if (pointerId) {
  5653. return;
  5654. }
  5655. pointerId = evt.pointerId;
  5656. previousPosition = {
  5657. x: evt.clientX,
  5658. y: evt.clientY
  5659. };
  5660. if (!noPreventDefault) {
  5661. evt.preventDefault();
  5662. }
  5663. };
  5664. this._onPointerUp = function (evt) {
  5665. previousPosition = null;
  5666. pointerId = null;
  5667. if (!noPreventDefault) {
  5668. evt.preventDefault();
  5669. }
  5670. };
  5671. this._onPointerMove = function (evt) {
  5672. if (!previousPosition) {
  5673. return;
  5674. }
  5675. if (pointerId !== evt.pointerId) {
  5676. return;
  5677. }
  5678. if (pinchStarted) {
  5679. return;
  5680. }
  5681. var offsetX = evt.clientX - previousPosition.x;
  5682. var offsetY = evt.clientY - previousPosition.y;
  5683. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5684. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5685. previousPosition = {
  5686. x: evt.clientX,
  5687. y: evt.clientY
  5688. };
  5689. if (!noPreventDefault) {
  5690. evt.preventDefault();
  5691. }
  5692. };
  5693. this._onMouseMove = function (evt) {
  5694. if (!engine.isPointerLock) {
  5695. return;
  5696. }
  5697. if (pinchStarted) {
  5698. return;
  5699. }
  5700. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5701. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5702. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5703. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5704. if (!noPreventDefault) {
  5705. evt.preventDefault();
  5706. }
  5707. };
  5708. this._wheel = function (event) {
  5709. var delta = 0;
  5710. if (event.wheelDelta) {
  5711. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5712. } else if (event.detail) {
  5713. delta = -event.detail / _this.wheelPrecision;
  5714. }
  5715. if (delta)
  5716. _this.inertialRadiusOffset += delta;
  5717. if (event.preventDefault) {
  5718. if (!noPreventDefault) {
  5719. event.preventDefault();
  5720. }
  5721. }
  5722. };
  5723. this._onKeyDown = function (evt) {
  5724. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5725. var index = _this._keys.indexOf(evt.keyCode);
  5726. if (index === -1) {
  5727. _this._keys.push(evt.keyCode);
  5728. }
  5729. if (evt.preventDefault) {
  5730. if (!noPreventDefault) {
  5731. evt.preventDefault();
  5732. }
  5733. }
  5734. }
  5735. };
  5736. this._onKeyUp = function (evt) {
  5737. 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) {
  5738. var index = _this._keys.indexOf(evt.keyCode);
  5739. if (index >= 0) {
  5740. _this._keys.splice(index, 1);
  5741. }
  5742. if (evt.preventDefault) {
  5743. if (!noPreventDefault) {
  5744. evt.preventDefault();
  5745. }
  5746. }
  5747. }
  5748. };
  5749. this._onLostFocus = function () {
  5750. _this._keys = [];
  5751. pointerId = null;
  5752. };
  5753. this._onGestureStart = function (e) {
  5754. if (window.MSGesture === undefined) {
  5755. return;
  5756. }
  5757. if (!_this._MSGestureHandler) {
  5758. _this._MSGestureHandler = new MSGesture();
  5759. _this._MSGestureHandler.target = element;
  5760. }
  5761. _this._MSGestureHandler.addPointer(e.pointerId);
  5762. };
  5763. this._onGesture = function (e) {
  5764. _this.radius *= e.scale;
  5765. if (e.preventDefault) {
  5766. if (!noPreventDefault) {
  5767. e.stopPropagation();
  5768. e.preventDefault();
  5769. }
  5770. }
  5771. };
  5772. this._reset = function () {
  5773. _this._keys = [];
  5774. _this.inertialAlphaOffset = 0;
  5775. _this.inertialBetaOffset = 0;
  5776. _this.inertialRadiusOffset = 0;
  5777. previousPosition = null;
  5778. pointerId = null;
  5779. };
  5780. this._touchStart = function (event) {
  5781. if (event.touches.length == 2) {
  5782. pinchStarted = true;
  5783. _this._pinchStart(event);
  5784. }
  5785. };
  5786. this._touchMove = function (event) {
  5787. if (pinchStarted) {
  5788. _this._pinchMove(event);
  5789. }
  5790. };
  5791. this._touchEnd = function (event) {
  5792. if (pinchStarted) {
  5793. _this._pinchEnd(event);
  5794. }
  5795. };
  5796. this._pinchStart = function (event) {
  5797. pinchPointX1 = event.touches[0].clientX;
  5798. pinchPointX2 = event.touches[1].clientX;
  5799. pinchStarted = true;
  5800. };
  5801. this._pinchMove = function (event) {
  5802. var delta = 0;
  5803. var direction = 1;
  5804. var distanceXOrigine, distanceXNow;
  5805. if (event.touches.length != 2)
  5806. return;
  5807. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5808. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5809. if (distanceXNow < distanceXOrigine) {
  5810. direction = -1;
  5811. }
  5812. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5813. _this.inertialRadiusOffset += delta;
  5814. pinchPointX1 = event.touches[0].clientX;
  5815. pinchPointX2 = event.touches[1].clientX;
  5816. };
  5817. this._pinchEnd = function (event) {
  5818. pinchStarted = false;
  5819. };
  5820. }
  5821. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5822. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5823. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5824. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5825. element.addEventListener("mousemove", this._onMouseMove, false);
  5826. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5827. element.addEventListener("MSGestureChange", this._onGesture, false);
  5828. element.addEventListener('mousewheel', this._wheel, false);
  5829. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5830. element.addEventListener('touchstart', this._touchStart, false);
  5831. element.addEventListener('touchmove', this._touchMove, false);
  5832. element.addEventListener('touchend', this._touchEnd, false);
  5833. BABYLON.Tools.RegisterTopRootEvents([
  5834. { name: "keydown", handler: this._onKeyDown },
  5835. { name: "keyup", handler: this._onKeyUp },
  5836. { name: "blur", handler: this._onLostFocus }
  5837. ]);
  5838. };
  5839. ArcRotateCamera.prototype.detachControl = function (element) {
  5840. if (this._attachedElement != element) {
  5841. return;
  5842. }
  5843. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5844. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5845. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5846. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5847. element.removeEventListener("mousemove", this._onMouseMove);
  5848. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5849. element.removeEventListener("MSGestureChange", this._onGesture);
  5850. element.removeEventListener('mousewheel', this._wheel);
  5851. element.removeEventListener('DOMMouseScroll', this._wheel);
  5852. element.removeEventListener('touchstart', this._touchStart);
  5853. element.removeEventListener('touchmove', this._touchMove);
  5854. element.removeEventListener('touchend', this._touchEnd);
  5855. BABYLON.Tools.UnregisterTopRootEvents([
  5856. { name: "keydown", handler: this._onKeyDown },
  5857. { name: "keyup", handler: this._onKeyUp },
  5858. { name: "blur", handler: this._onLostFocus }
  5859. ]);
  5860. this._MSGestureHandler = null;
  5861. this._attachedElement = null;
  5862. if (this._reset) {
  5863. this._reset();
  5864. }
  5865. };
  5866. ArcRotateCamera.prototype._update = function () {
  5867. for (var index = 0; index < this._keys.length; index++) {
  5868. var keyCode = this._keys[index];
  5869. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5870. this.inertialAlphaOffset -= 0.01;
  5871. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5872. this.inertialBetaOffset -= 0.01;
  5873. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5874. this.inertialAlphaOffset += 0.01;
  5875. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5876. this.inertialBetaOffset += 0.01;
  5877. }
  5878. }
  5879. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5880. this.alpha += this.inertialAlphaOffset;
  5881. this.beta += this.inertialBetaOffset;
  5882. this.radius -= this.inertialRadiusOffset;
  5883. this.inertialAlphaOffset *= this.inertia;
  5884. this.inertialBetaOffset *= this.inertia;
  5885. this.inertialRadiusOffset *= this.inertia;
  5886. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5887. this.inertialAlphaOffset = 0;
  5888. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5889. this.inertialBetaOffset = 0;
  5890. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5891. this.inertialRadiusOffset = 0;
  5892. }
  5893. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5894. this.alpha = this.lowerAlphaLimit;
  5895. }
  5896. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5897. this.alpha = this.upperAlphaLimit;
  5898. }
  5899. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5900. this.beta = this.lowerBetaLimit;
  5901. }
  5902. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5903. this.beta = this.upperBetaLimit;
  5904. }
  5905. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5906. this.radius = this.lowerRadiusLimit;
  5907. }
  5908. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5909. this.radius = this.upperRadiusLimit;
  5910. }
  5911. };
  5912. ArcRotateCamera.prototype.setPosition = function (position) {
  5913. var radiusv3 = position.subtract(this._getTargetPosition());
  5914. this.radius = radiusv3.length();
  5915. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5916. if (radiusv3.z < 0) {
  5917. this.alpha = 2 * Math.PI - this.alpha;
  5918. }
  5919. this.beta = Math.acos(radiusv3.y / this.radius);
  5920. };
  5921. ArcRotateCamera.prototype._getViewMatrix = function () {
  5922. var cosa = Math.cos(this.alpha);
  5923. var sina = Math.sin(this.alpha);
  5924. var cosb = Math.cos(this.beta);
  5925. var sinb = Math.sin(this.beta);
  5926. var target = this._getTargetPosition();
  5927. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5928. if (this.checkCollisions) {
  5929. this._collider.radius = this.collisionRadius;
  5930. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5931. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5932. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5933. this.position.copyFrom(this._previousPosition);
  5934. this.alpha = this._previousAlpha;
  5935. this.beta = this._previousBeta;
  5936. this.radius = this._previousRadius;
  5937. if (this.onCollide) {
  5938. this.onCollide(this._collider.collidedMesh);
  5939. }
  5940. }
  5941. }
  5942. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5943. this._previousAlpha = this.alpha;
  5944. this._previousBeta = this.beta;
  5945. this._previousRadius = this.radius;
  5946. this._previousPosition.copyFrom(this.position);
  5947. return this._viewMatrix;
  5948. };
  5949. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5950. meshes = meshes || this.getScene().meshes;
  5951. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5952. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5953. this.radius = distance * this.zoomOnFactor;
  5954. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5955. };
  5956. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5957. var meshesOrMinMaxVector;
  5958. var distance;
  5959. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5960. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5961. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5962. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5963. } else {
  5964. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5965. distance = meshesOrMinMaxVectorAndDistance.distance;
  5966. }
  5967. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5968. this.maxZ = distance * 2;
  5969. };
  5970. return ArcRotateCamera;
  5971. })(BABYLON.Camera);
  5972. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5973. })(BABYLON || (BABYLON = {}));
  5974. var BABYLON;
  5975. (function (BABYLON) {
  5976. var Scene = (function () {
  5977. function Scene(engine) {
  5978. this.autoClear = true;
  5979. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5980. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5981. this.forceWireframe = false;
  5982. this.cameraToUseForPointers = null;
  5983. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5984. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5985. this.fogDensity = 0.1;
  5986. this.fogStart = 0;
  5987. this.fogEnd = 1000.0;
  5988. this.lightsEnabled = true;
  5989. this.lights = new Array();
  5990. this.cameras = new Array();
  5991. this.activeCameras = new Array();
  5992. this.meshes = new Array();
  5993. this._geometries = new Array();
  5994. this.materials = new Array();
  5995. this.multiMaterials = new Array();
  5996. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5997. this.texturesEnabled = true;
  5998. this.textures = new Array();
  5999. this.particlesEnabled = true;
  6000. this.particleSystems = new Array();
  6001. this.spriteManagers = new Array();
  6002. this.layers = new Array();
  6003. this.skeletons = new Array();
  6004. this.lensFlareSystems = new Array();
  6005. this.collisionsEnabled = true;
  6006. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6007. this.postProcessesEnabled = true;
  6008. this.renderTargetsEnabled = true;
  6009. this.customRenderTargets = new Array();
  6010. this.importedMeshesFiles = new Array();
  6011. this._actionManagers = new Array();
  6012. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6013. this._totalVertices = 0;
  6014. this._activeVertices = 0;
  6015. this._activeParticles = 0;
  6016. this._lastFrameDuration = 0;
  6017. this._evaluateActiveMeshesDuration = 0;
  6018. this._renderTargetsDuration = 0;
  6019. this._particlesDuration = 0;
  6020. this._renderDuration = 0;
  6021. this._spritesDuration = 0;
  6022. this._animationRatio = 0;
  6023. this._renderId = 0;
  6024. this._executeWhenReadyTimeoutId = -1;
  6025. this._toBeDisposed = new BABYLON.SmartArray(256);
  6026. this._onReadyCallbacks = new Array();
  6027. this._pendingData = [];
  6028. this._onBeforeRenderCallbacks = new Array();
  6029. this._activeMeshes = new BABYLON.SmartArray(256);
  6030. this._processedMaterials = new BABYLON.SmartArray(256);
  6031. this._renderTargets = new BABYLON.SmartArray(256);
  6032. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6033. this._activeSkeletons = new BABYLON.SmartArray(32);
  6034. this._activeAnimatables = new Array();
  6035. this._transformMatrix = BABYLON.Matrix.Zero();
  6036. this._scaledPosition = BABYLON.Vector3.Zero();
  6037. this._scaledVelocity = BABYLON.Vector3.Zero();
  6038. this._engine = engine;
  6039. engine.scenes.push(this);
  6040. this._renderingManager = new BABYLON.RenderingManager(this);
  6041. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6042. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6043. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6044. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6045. this.attachControl();
  6046. }
  6047. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6048. get: function () {
  6049. return this._meshUnderPointer;
  6050. },
  6051. enumerable: true,
  6052. configurable: true
  6053. });
  6054. Object.defineProperty(Scene.prototype, "pointerX", {
  6055. get: function () {
  6056. return this._pointerX;
  6057. },
  6058. enumerable: true,
  6059. configurable: true
  6060. });
  6061. Object.defineProperty(Scene.prototype, "pointerY", {
  6062. get: function () {
  6063. return this._pointerY;
  6064. },
  6065. enumerable: true,
  6066. configurable: true
  6067. });
  6068. Scene.prototype.getBoundingBoxRenderer = function () {
  6069. return this._boundingBoxRenderer;
  6070. };
  6071. Scene.prototype.getOutlineRenderer = function () {
  6072. return this._outlineRenderer;
  6073. };
  6074. Scene.prototype.getEngine = function () {
  6075. return this._engine;
  6076. };
  6077. Scene.prototype.getTotalVertices = function () {
  6078. return this._totalVertices;
  6079. };
  6080. Scene.prototype.getActiveVertices = function () {
  6081. return this._activeVertices;
  6082. };
  6083. Scene.prototype.getActiveParticles = function () {
  6084. return this._activeParticles;
  6085. };
  6086. Scene.prototype.getLastFrameDuration = function () {
  6087. return this._lastFrameDuration;
  6088. };
  6089. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6090. return this._evaluateActiveMeshesDuration;
  6091. };
  6092. Scene.prototype.getActiveMeshes = function () {
  6093. return this._activeMeshes;
  6094. };
  6095. Scene.prototype.getRenderTargetsDuration = function () {
  6096. return this._renderTargetsDuration;
  6097. };
  6098. Scene.prototype.getRenderDuration = function () {
  6099. return this._renderDuration;
  6100. };
  6101. Scene.prototype.getParticlesDuration = function () {
  6102. return this._particlesDuration;
  6103. };
  6104. Scene.prototype.getSpritesDuration = function () {
  6105. return this._spritesDuration;
  6106. };
  6107. Scene.prototype.getAnimationRatio = function () {
  6108. return this._animationRatio;
  6109. };
  6110. Scene.prototype.getRenderId = function () {
  6111. return this._renderId;
  6112. };
  6113. Scene.prototype._updatePointerPosition = function (evt) {
  6114. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6115. this._pointerX = evt.clientX - canvasRect.left;
  6116. this._pointerY = evt.clientY - canvasRect.top;
  6117. if (this.cameraToUseForPointers) {
  6118. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6119. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6120. }
  6121. };
  6122. Scene.prototype.attachControl = function () {
  6123. var _this = this;
  6124. this._onPointerMove = function (evt) {
  6125. var canvas = _this._engine.getRenderingCanvas();
  6126. _this._updatePointerPosition(evt);
  6127. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6128. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6129. }, false, _this.cameraToUseForPointers);
  6130. if (pickResult.hit) {
  6131. _this._meshUnderPointer = pickResult.pickedMesh;
  6132. _this.setPointerOverMesh(pickResult.pickedMesh);
  6133. canvas.style.cursor = "pointer";
  6134. } else {
  6135. _this.setPointerOverMesh(null);
  6136. canvas.style.cursor = "";
  6137. _this._meshUnderPointer = null;
  6138. }
  6139. };
  6140. this._onPointerDown = function (evt) {
  6141. var predicate = null;
  6142. if (!_this.onPointerDown) {
  6143. predicate = function (mesh) {
  6144. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6145. };
  6146. }
  6147. _this._updatePointerPosition(evt);
  6148. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6149. if (pickResult.hit) {
  6150. if (pickResult.pickedMesh.actionManager) {
  6151. switch (evt.button) {
  6152. case 0:
  6153. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6154. break;
  6155. case 1:
  6156. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6157. break;
  6158. case 2:
  6159. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6160. break;
  6161. }
  6162. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6163. }
  6164. }
  6165. if (_this.onPointerDown) {
  6166. _this.onPointerDown(evt, pickResult);
  6167. }
  6168. };
  6169. this._onKeyDown = function (evt) {
  6170. if (_this.actionManager) {
  6171. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6172. }
  6173. };
  6174. this._onKeyUp = function (evt) {
  6175. if (_this.actionManager) {
  6176. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6177. }
  6178. };
  6179. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6180. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6181. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6182. window.addEventListener("keydown", this._onKeyDown, false);
  6183. window.addEventListener("keyup", this._onKeyUp, false);
  6184. };
  6185. Scene.prototype.detachControl = function () {
  6186. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6187. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6188. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6189. window.removeEventListener("keydown", this._onKeyDown);
  6190. window.removeEventListener("keyup", this._onKeyUp);
  6191. };
  6192. Scene.prototype.isReady = function () {
  6193. if (this._pendingData.length > 0) {
  6194. return false;
  6195. }
  6196. for (var index = 0; index < this._geometries.length; index++) {
  6197. var geometry = this._geometries[index];
  6198. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6199. return false;
  6200. }
  6201. }
  6202. for (index = 0; index < this.meshes.length; index++) {
  6203. var mesh = this.meshes[index];
  6204. if (!mesh.isReady()) {
  6205. return false;
  6206. }
  6207. var mat = mesh.material;
  6208. if (mat) {
  6209. if (!mat.isReady(mesh)) {
  6210. return false;
  6211. }
  6212. }
  6213. }
  6214. return true;
  6215. };
  6216. Scene.prototype.registerBeforeRender = function (func) {
  6217. this._onBeforeRenderCallbacks.push(func);
  6218. };
  6219. Scene.prototype.unregisterBeforeRender = function (func) {
  6220. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6221. if (index > -1) {
  6222. this._onBeforeRenderCallbacks.splice(index, 1);
  6223. }
  6224. };
  6225. Scene.prototype._addPendingData = function (data) {
  6226. this._pendingData.push(data);
  6227. };
  6228. Scene.prototype._removePendingData = function (data) {
  6229. var index = this._pendingData.indexOf(data);
  6230. if (index !== -1) {
  6231. this._pendingData.splice(index, 1);
  6232. }
  6233. };
  6234. Scene.prototype.getWaitingItemsCount = function () {
  6235. return this._pendingData.length;
  6236. };
  6237. Scene.prototype.executeWhenReady = function (func) {
  6238. var _this = this;
  6239. this._onReadyCallbacks.push(func);
  6240. if (this._executeWhenReadyTimeoutId !== -1) {
  6241. return;
  6242. }
  6243. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6244. _this._checkIsReady();
  6245. }, 150);
  6246. };
  6247. Scene.prototype._checkIsReady = function () {
  6248. var _this = this;
  6249. if (this.isReady()) {
  6250. this._onReadyCallbacks.forEach(function (func) {
  6251. func();
  6252. });
  6253. this._onReadyCallbacks = [];
  6254. this._executeWhenReadyTimeoutId = -1;
  6255. return;
  6256. }
  6257. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6258. _this._checkIsReady();
  6259. }, 150);
  6260. };
  6261. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6262. if (speedRatio === undefined) {
  6263. speedRatio = 1.0;
  6264. }
  6265. this.stopAnimation(target);
  6266. if (!animatable) {
  6267. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6268. }
  6269. if (target.animations) {
  6270. animatable.appendAnimations(target, target.animations);
  6271. }
  6272. if (target.getAnimatables) {
  6273. var animatables = target.getAnimatables();
  6274. for (var index = 0; index < animatables.length; index++) {
  6275. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6276. }
  6277. }
  6278. return animatable;
  6279. };
  6280. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6281. if (speedRatio === undefined) {
  6282. speedRatio = 1.0;
  6283. }
  6284. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6285. return animatable;
  6286. };
  6287. Scene.prototype.getAnimatableByTarget = function (target) {
  6288. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6289. if (this._activeAnimatables[index].target === target) {
  6290. return this._activeAnimatables[index];
  6291. }
  6292. }
  6293. return null;
  6294. };
  6295. Scene.prototype.stopAnimation = function (target) {
  6296. var animatable = this.getAnimatableByTarget(target);
  6297. if (animatable) {
  6298. animatable.stop();
  6299. }
  6300. };
  6301. Scene.prototype._animate = function () {
  6302. if (!this._animationStartDate) {
  6303. this._animationStartDate = new Date().getTime();
  6304. }
  6305. var now = new Date().getTime();
  6306. var delay = now - this._animationStartDate;
  6307. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6308. if (!this._activeAnimatables[index]._animate(delay)) {
  6309. this._activeAnimatables.splice(index, 1);
  6310. index--;
  6311. }
  6312. }
  6313. };
  6314. Scene.prototype.getViewMatrix = function () {
  6315. return this._viewMatrix;
  6316. };
  6317. Scene.prototype.getProjectionMatrix = function () {
  6318. return this._projectionMatrix;
  6319. };
  6320. Scene.prototype.getTransformMatrix = function () {
  6321. return this._transformMatrix;
  6322. };
  6323. Scene.prototype.setTransformMatrix = function (view, projection) {
  6324. this._viewMatrix = view;
  6325. this._projectionMatrix = projection;
  6326. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6327. };
  6328. Scene.prototype.setActiveCameraByID = function (id) {
  6329. var camera = this.getCameraByID(id);
  6330. if (camera) {
  6331. this.activeCamera = camera;
  6332. return camera;
  6333. }
  6334. return null;
  6335. };
  6336. Scene.prototype.setActiveCameraByName = function (name) {
  6337. var camera = this.getCameraByName(name);
  6338. if (camera) {
  6339. this.activeCamera = camera;
  6340. return camera;
  6341. }
  6342. return null;
  6343. };
  6344. Scene.prototype.getMaterialByID = function (id) {
  6345. for (var index = 0; index < this.materials.length; index++) {
  6346. if (this.materials[index].id === id) {
  6347. return this.materials[index];
  6348. }
  6349. }
  6350. return null;
  6351. };
  6352. Scene.prototype.getMaterialByName = function (name) {
  6353. for (var index = 0; index < this.materials.length; index++) {
  6354. if (this.materials[index].name === name) {
  6355. return this.materials[index];
  6356. }
  6357. }
  6358. return null;
  6359. };
  6360. Scene.prototype.getCameraByID = function (id) {
  6361. for (var index = 0; index < this.cameras.length; index++) {
  6362. if (this.cameras[index].id === id) {
  6363. return this.cameras[index];
  6364. }
  6365. }
  6366. return null;
  6367. };
  6368. Scene.prototype.getCameraByName = function (name) {
  6369. for (var index = 0; index < this.cameras.length; index++) {
  6370. if (this.cameras[index].name === name) {
  6371. return this.cameras[index];
  6372. }
  6373. }
  6374. return null;
  6375. };
  6376. Scene.prototype.getLightByName = function (name) {
  6377. for (var index = 0; index < this.lights.length; index++) {
  6378. if (this.lights[index].name === name) {
  6379. return this.lights[index];
  6380. }
  6381. }
  6382. return null;
  6383. };
  6384. Scene.prototype.getLightByID = function (id) {
  6385. for (var index = 0; index < this.lights.length; index++) {
  6386. if (this.lights[index].id === id) {
  6387. return this.lights[index];
  6388. }
  6389. }
  6390. return null;
  6391. };
  6392. Scene.prototype.getGeometryByID = function (id) {
  6393. for (var index = 0; index < this._geometries.length; index++) {
  6394. if (this._geometries[index].id === id) {
  6395. return this._geometries[index];
  6396. }
  6397. }
  6398. return null;
  6399. };
  6400. Scene.prototype.pushGeometry = function (geometry, force) {
  6401. if (!force && this.getGeometryByID(geometry.id)) {
  6402. return false;
  6403. }
  6404. this._geometries.push(geometry);
  6405. return true;
  6406. };
  6407. Scene.prototype.getGeometries = function () {
  6408. return this._geometries;
  6409. };
  6410. Scene.prototype.getMeshByID = function (id) {
  6411. for (var index = 0; index < this.meshes.length; index++) {
  6412. if (this.meshes[index].id === id) {
  6413. return this.meshes[index];
  6414. }
  6415. }
  6416. return null;
  6417. };
  6418. Scene.prototype.getLastMeshByID = function (id) {
  6419. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6420. if (this.meshes[index].id === id) {
  6421. return this.meshes[index];
  6422. }
  6423. }
  6424. return null;
  6425. };
  6426. Scene.prototype.getLastEntryByID = function (id) {
  6427. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6428. if (this.meshes[index].id === id) {
  6429. return this.meshes[index];
  6430. }
  6431. }
  6432. for (index = this.cameras.length - 1; index >= 0; index--) {
  6433. if (this.cameras[index].id === id) {
  6434. return this.cameras[index];
  6435. }
  6436. }
  6437. for (index = this.lights.length - 1; index >= 0; index--) {
  6438. if (this.lights[index].id === id) {
  6439. return this.lights[index];
  6440. }
  6441. }
  6442. return null;
  6443. };
  6444. Scene.prototype.getMeshByName = function (name) {
  6445. for (var index = 0; index < this.meshes.length; index++) {
  6446. if (this.meshes[index].name === name) {
  6447. return this.meshes[index];
  6448. }
  6449. }
  6450. return null;
  6451. };
  6452. Scene.prototype.getLastSkeletonByID = function (id) {
  6453. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6454. if (this.skeletons[index].id === id) {
  6455. return this.skeletons[index];
  6456. }
  6457. }
  6458. return null;
  6459. };
  6460. Scene.prototype.getSkeletonById = function (id) {
  6461. for (var index = 0; index < this.skeletons.length; index++) {
  6462. if (this.skeletons[index].id === id) {
  6463. return this.skeletons[index];
  6464. }
  6465. }
  6466. return null;
  6467. };
  6468. Scene.prototype.getSkeletonByName = function (name) {
  6469. for (var index = 0; index < this.skeletons.length; index++) {
  6470. if (this.skeletons[index].name === name) {
  6471. return this.skeletons[index];
  6472. }
  6473. }
  6474. return null;
  6475. };
  6476. Scene.prototype.isActiveMesh = function (mesh) {
  6477. return (this._activeMeshes.indexOf(mesh) !== -1);
  6478. };
  6479. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6480. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6481. var material = subMesh.getMaterial();
  6482. if (mesh.showSubMeshesBoundingBox) {
  6483. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6484. }
  6485. if (material) {
  6486. if (material.getRenderTargetTextures) {
  6487. if (this._processedMaterials.indexOf(material) === -1) {
  6488. this._processedMaterials.push(material);
  6489. this._renderTargets.concat(material.getRenderTargetTextures());
  6490. }
  6491. }
  6492. this._activeVertices += subMesh.verticesCount;
  6493. this._renderingManager.dispatch(subMesh);
  6494. }
  6495. }
  6496. };
  6497. Scene.prototype._evaluateActiveMeshes = function () {
  6498. this._activeMeshes.reset();
  6499. this._renderingManager.reset();
  6500. this._processedMaterials.reset();
  6501. this._activeParticleSystems.reset();
  6502. this._activeSkeletons.reset();
  6503. this._boundingBoxRenderer.reset();
  6504. if (!this._frustumPlanes) {
  6505. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6506. } else {
  6507. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6508. }
  6509. var meshes;
  6510. var len;
  6511. if (this._selectionOctree) {
  6512. var selection = this._selectionOctree.select(this._frustumPlanes);
  6513. meshes = selection.data;
  6514. len = selection.length;
  6515. } else {
  6516. len = this.meshes.length;
  6517. meshes = this.meshes;
  6518. }
  6519. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6520. var mesh = meshes[meshIndex];
  6521. this._totalVertices += mesh.getTotalVertices();
  6522. if (!mesh.isReady()) {
  6523. continue;
  6524. }
  6525. mesh.computeWorldMatrix();
  6526. mesh._preActivate();
  6527. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6528. this._meshesForIntersections.pushNoDuplicate(mesh);
  6529. }
  6530. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6531. this._activeMeshes.push(mesh);
  6532. mesh._activate(this._renderId);
  6533. this._activeMesh(mesh);
  6534. }
  6535. }
  6536. var beforeParticlesDate = new Date().getTime();
  6537. if (this.particlesEnabled) {
  6538. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6539. var particleSystem = this.particleSystems[particleIndex];
  6540. if (!particleSystem.isStarted()) {
  6541. continue;
  6542. }
  6543. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6544. this._activeParticleSystems.push(particleSystem);
  6545. particleSystem.animate();
  6546. }
  6547. }
  6548. }
  6549. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6550. };
  6551. Scene.prototype._activeMesh = function (mesh) {
  6552. if (mesh.skeleton) {
  6553. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6554. }
  6555. if (mesh.showBoundingBox) {
  6556. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6557. }
  6558. if (mesh.subMeshes) {
  6559. var len;
  6560. var subMeshes;
  6561. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6562. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6563. len = intersections.length;
  6564. subMeshes = intersections.data;
  6565. } else {
  6566. subMeshes = mesh.subMeshes;
  6567. len = subMeshes.length;
  6568. }
  6569. for (var subIndex = 0; subIndex < len; subIndex++) {
  6570. var subMesh = subMeshes[subIndex];
  6571. this._evaluateSubMesh(subMesh, mesh);
  6572. }
  6573. }
  6574. };
  6575. Scene.prototype.updateTransformMatrix = function (force) {
  6576. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6577. };
  6578. Scene.prototype._renderForCamera = function (camera) {
  6579. var engine = this._engine;
  6580. this.activeCamera = camera;
  6581. if (!this.activeCamera)
  6582. throw new Error("Active camera not set");
  6583. engine.setViewport(this.activeCamera.viewport);
  6584. this._renderId++;
  6585. this.updateTransformMatrix();
  6586. if (this.beforeCameraRender) {
  6587. this.beforeCameraRender(this.activeCamera);
  6588. }
  6589. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6590. this._evaluateActiveMeshes();
  6591. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6592. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6593. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6594. skeleton.prepare();
  6595. }
  6596. var beforeRenderTargetDate = new Date().getTime();
  6597. if (this.renderTargetsEnabled) {
  6598. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6599. var renderTarget = this._renderTargets.data[renderIndex];
  6600. if (renderTarget._shouldRender()) {
  6601. this._renderId++;
  6602. renderTarget.render();
  6603. }
  6604. }
  6605. this._renderId++;
  6606. }
  6607. if (this._renderTargets.length > 0) {
  6608. engine.restoreDefaultFramebuffer();
  6609. }
  6610. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6611. this.postProcessManager._prepareFrame();
  6612. var beforeRenderDate = new Date().getTime();
  6613. if (this.layers.length) {
  6614. engine.setDepthBuffer(false);
  6615. var layerIndex;
  6616. var layer;
  6617. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6618. layer = this.layers[layerIndex];
  6619. if (layer.isBackground) {
  6620. layer.render();
  6621. }
  6622. }
  6623. engine.setDepthBuffer(true);
  6624. }
  6625. this._renderingManager.render(null, null, true, true);
  6626. this._boundingBoxRenderer.render();
  6627. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6628. this.lensFlareSystems[lensFlareSystemIndex].render();
  6629. }
  6630. if (this.layers.length) {
  6631. engine.setDepthBuffer(false);
  6632. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6633. layer = this.layers[layerIndex];
  6634. if (!layer.isBackground) {
  6635. layer.render();
  6636. }
  6637. }
  6638. engine.setDepthBuffer(true);
  6639. }
  6640. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6641. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6642. this.activeCamera._updateFromScene();
  6643. this._renderTargets.reset();
  6644. if (this.afterCameraRender) {
  6645. this.afterCameraRender(this.activeCamera);
  6646. }
  6647. };
  6648. Scene.prototype._processSubCameras = function (camera) {
  6649. if (camera.subCameras.length == 0) {
  6650. this._renderForCamera(camera);
  6651. return;
  6652. }
  6653. for (var index = 0; index < camera.subCameras.length; index++) {
  6654. this._renderForCamera(camera.subCameras[index]);
  6655. }
  6656. this.activeCamera = camera;
  6657. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6658. this.activeCamera._updateFromScene();
  6659. };
  6660. Scene.prototype._checkIntersections = function () {
  6661. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6662. var sourceMesh = this._meshesForIntersections.data[index];
  6663. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6664. var action = sourceMesh.actionManager.actions[actionIndex];
  6665. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6666. var otherMesh = action.getTriggerParameter();
  6667. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6668. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6669. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6670. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6671. sourceMesh._intersectionsInProgress.push(otherMesh);
  6672. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6673. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6674. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6675. if (indexOfOther > -1) {
  6676. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6677. }
  6678. }
  6679. }
  6680. }
  6681. }
  6682. };
  6683. Scene.prototype.render = function () {
  6684. var startDate = new Date().getTime();
  6685. this._particlesDuration = 0;
  6686. this._spritesDuration = 0;
  6687. this._activeParticles = 0;
  6688. this._renderDuration = 0;
  6689. this._evaluateActiveMeshesDuration = 0;
  6690. this._totalVertices = 0;
  6691. this._activeVertices = 0;
  6692. this._meshesForIntersections.reset();
  6693. if (this.actionManager) {
  6694. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6695. }
  6696. if (this.beforeRender) {
  6697. this.beforeRender();
  6698. }
  6699. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6700. this._onBeforeRenderCallbacks[callbackIndex]();
  6701. }
  6702. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6703. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6704. this._animate();
  6705. if (this._physicsEngine) {
  6706. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6707. }
  6708. var beforeRenderTargetDate = new Date().getTime();
  6709. var engine = this.getEngine();
  6710. if (this.renderTargetsEnabled) {
  6711. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6712. var renderTarget = this.customRenderTargets[customIndex];
  6713. if (renderTarget._shouldRender()) {
  6714. this._renderId++;
  6715. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6716. if (!this.activeCamera)
  6717. throw new Error("Active camera not set");
  6718. engine.setViewport(this.activeCamera.viewport);
  6719. this.updateTransformMatrix();
  6720. renderTarget.render();
  6721. }
  6722. }
  6723. this._renderId++;
  6724. }
  6725. if (this.customRenderTargets.length > 0) {
  6726. engine.restoreDefaultFramebuffer();
  6727. }
  6728. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6729. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6730. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6731. var light = this.lights[lightIndex];
  6732. var shadowGenerator = light.getShadowGenerator();
  6733. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6734. this._renderTargets.push(shadowGenerator.getShadowMap());
  6735. }
  6736. }
  6737. this.postProcessRenderPipelineManager.update();
  6738. if (this.activeCameras.length > 0) {
  6739. var currentRenderId = this._renderId;
  6740. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6741. this._renderId = currentRenderId;
  6742. this._processSubCameras(this.activeCameras[cameraIndex]);
  6743. }
  6744. } else {
  6745. if (!this.activeCamera) {
  6746. throw new Error("No camera defined");
  6747. }
  6748. this._processSubCameras(this.activeCamera);
  6749. }
  6750. this._checkIntersections();
  6751. if (this.afterRender) {
  6752. this.afterRender();
  6753. }
  6754. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6755. this._toBeDisposed.data[index].dispose();
  6756. this._toBeDisposed[index] = null;
  6757. }
  6758. this._toBeDisposed.reset();
  6759. this._lastFrameDuration = new Date().getTime() - startDate;
  6760. };
  6761. Scene.prototype.dispose = function () {
  6762. this.beforeRender = null;
  6763. this.afterRender = null;
  6764. this.skeletons = [];
  6765. this._boundingBoxRenderer.dispose();
  6766. if (this.onDispose) {
  6767. this.onDispose();
  6768. }
  6769. this.detachControl();
  6770. var canvas = this._engine.getRenderingCanvas();
  6771. var index;
  6772. for (index = 0; index < this.cameras.length; index++) {
  6773. this.cameras[index].detachControl(canvas);
  6774. }
  6775. while (this.lights.length) {
  6776. this.lights[0].dispose();
  6777. }
  6778. while (this.meshes.length) {
  6779. this.meshes[0].dispose(true);
  6780. }
  6781. while (this.cameras.length) {
  6782. this.cameras[0].dispose();
  6783. }
  6784. while (this.materials.length) {
  6785. this.materials[0].dispose();
  6786. }
  6787. while (this.particleSystems.length) {
  6788. this.particleSystems[0].dispose();
  6789. }
  6790. while (this.spriteManagers.length) {
  6791. this.spriteManagers[0].dispose();
  6792. }
  6793. while (this.layers.length) {
  6794. this.layers[0].dispose();
  6795. }
  6796. while (this.textures.length) {
  6797. this.textures[0].dispose();
  6798. }
  6799. this.postProcessManager.dispose();
  6800. if (this._physicsEngine) {
  6801. this.disablePhysicsEngine();
  6802. }
  6803. index = this._engine.scenes.indexOf(this);
  6804. if (index > -1) {
  6805. this._engine.scenes.splice(index, 1);
  6806. }
  6807. this._engine.wipeCaches();
  6808. };
  6809. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6810. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6811. position.divideToRef(collider.radius, this._scaledPosition);
  6812. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6813. collider.retry = 0;
  6814. collider.initialVelocity = this._scaledVelocity;
  6815. collider.initialPosition = this._scaledPosition;
  6816. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6817. finalPosition.multiplyInPlace(collider.radius);
  6818. };
  6819. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6820. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6821. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6822. if (collider.retry >= maximumRetry) {
  6823. finalPosition.copyFrom(position);
  6824. return;
  6825. }
  6826. collider._initialize(position, velocity, closeDistance);
  6827. for (var index = 0; index < this.meshes.length; index++) {
  6828. var mesh = this.meshes[index];
  6829. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6830. mesh._checkCollision(collider);
  6831. }
  6832. }
  6833. if (!collider.collisionFound) {
  6834. position.addToRef(velocity, finalPosition);
  6835. return;
  6836. }
  6837. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6838. collider._getResponse(position, velocity);
  6839. }
  6840. if (velocity.length() <= closeDistance) {
  6841. finalPosition.copyFrom(position);
  6842. return;
  6843. }
  6844. collider.retry++;
  6845. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6846. };
  6847. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6848. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6849. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6850. if (!this._selectionOctree) {
  6851. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6852. }
  6853. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6854. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6855. for (var index = 0; index < this.meshes.length; index++) {
  6856. var mesh = this.meshes[index];
  6857. mesh.computeWorldMatrix(true);
  6858. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6859. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6860. BABYLON.Tools.CheckExtends(minBox, min, max);
  6861. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6862. }
  6863. this._selectionOctree.update(min, max, this.meshes);
  6864. return this._selectionOctree;
  6865. };
  6866. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6867. var engine = this._engine;
  6868. if (!camera) {
  6869. if (!this.activeCamera)
  6870. throw new Error("Active camera not set");
  6871. camera = this.activeCamera;
  6872. }
  6873. var cameraViewport = camera.viewport;
  6874. var viewport = cameraViewport.toGlobal(engine);
  6875. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6876. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6877. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6878. };
  6879. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6880. var pickingInfo = null;
  6881. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6882. var mesh = this.meshes[meshIndex];
  6883. if (predicate) {
  6884. if (!predicate(mesh)) {
  6885. continue;
  6886. }
  6887. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6888. continue;
  6889. }
  6890. var world = mesh.getWorldMatrix();
  6891. var ray = rayFunction(world);
  6892. var result = mesh.intersects(ray, fastCheck);
  6893. if (!result || !result.hit)
  6894. continue;
  6895. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6896. continue;
  6897. pickingInfo = result;
  6898. if (fastCheck) {
  6899. break;
  6900. }
  6901. }
  6902. return pickingInfo || new BABYLON.PickingInfo();
  6903. };
  6904. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6905. var _this = this;
  6906. return this._internalPick(function (world) {
  6907. return _this.createPickingRay(x, y, world, camera);
  6908. }, predicate, fastCheck);
  6909. };
  6910. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6911. var _this = this;
  6912. return this._internalPick(function (world) {
  6913. if (!_this._pickWithRayInverseMatrix) {
  6914. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6915. }
  6916. world.invertToRef(_this._pickWithRayInverseMatrix);
  6917. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6918. }, predicate, fastCheck);
  6919. };
  6920. Scene.prototype.setPointerOverMesh = function (mesh) {
  6921. if (this._pointerOverMesh === mesh) {
  6922. return;
  6923. }
  6924. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6925. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6926. }
  6927. this._pointerOverMesh = mesh;
  6928. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6929. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6930. }
  6931. };
  6932. Scene.prototype.getPointerOverMesh = function () {
  6933. return this._pointerOverMesh;
  6934. };
  6935. Scene.prototype.getPhysicsEngine = function () {
  6936. return this._physicsEngine;
  6937. };
  6938. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6939. if (this._physicsEngine) {
  6940. return true;
  6941. }
  6942. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6943. if (!this._physicsEngine.isSupported()) {
  6944. this._physicsEngine = null;
  6945. return false;
  6946. }
  6947. this._physicsEngine._initialize(gravity);
  6948. return true;
  6949. };
  6950. Scene.prototype.disablePhysicsEngine = function () {
  6951. if (!this._physicsEngine) {
  6952. return;
  6953. }
  6954. this._physicsEngine.dispose();
  6955. this._physicsEngine = undefined;
  6956. };
  6957. Scene.prototype.isPhysicsEnabled = function () {
  6958. return this._physicsEngine !== undefined;
  6959. };
  6960. Scene.prototype.setGravity = function (gravity) {
  6961. if (!this._physicsEngine) {
  6962. return;
  6963. }
  6964. this._physicsEngine._setGravity(gravity);
  6965. };
  6966. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6967. if (parts.parts) {
  6968. options = parts;
  6969. parts = parts.parts;
  6970. }
  6971. if (!this._physicsEngine) {
  6972. return null;
  6973. }
  6974. for (var index = 0; index < parts.length; index++) {
  6975. var mesh = parts[index].mesh;
  6976. mesh._physicImpostor = parts[index].impostor;
  6977. mesh._physicsMass = options.mass / parts.length;
  6978. mesh._physicsFriction = options.friction;
  6979. mesh._physicRestitution = options.restitution;
  6980. }
  6981. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6982. };
  6983. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6984. for (var index = 0; index < compound.parts.length; index++) {
  6985. var mesh = compound.parts[index].mesh;
  6986. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6987. this._physicsEngine._unregisterMesh(mesh);
  6988. }
  6989. };
  6990. Scene.prototype._getByTags = function (list, tagsQuery) {
  6991. if (tagsQuery === undefined) {
  6992. return list;
  6993. }
  6994. var listByTags = [];
  6995. for (var i in list) {
  6996. var item = list[i];
  6997. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6998. listByTags.push(item);
  6999. }
  7000. }
  7001. return listByTags;
  7002. };
  7003. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7004. return this._getByTags(this.meshes, tagsQuery);
  7005. };
  7006. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7007. return this._getByTags(this.cameras, tagsQuery);
  7008. };
  7009. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7010. return this._getByTags(this.lights, tagsQuery);
  7011. };
  7012. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7013. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7014. };
  7015. Scene.FOGMODE_NONE = 0;
  7016. Scene.FOGMODE_EXP = 1;
  7017. Scene.FOGMODE_EXP2 = 2;
  7018. Scene.FOGMODE_LINEAR = 3;
  7019. Scene.MinDeltaTime = 1.0;
  7020. Scene.MaxDeltaTime = 1000.0;
  7021. return Scene;
  7022. })();
  7023. BABYLON.Scene = Scene;
  7024. })(BABYLON || (BABYLON = {}));
  7025. var BABYLON;
  7026. (function (BABYLON) {
  7027. var VertexBuffer = (function () {
  7028. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7029. if (engine instanceof BABYLON.Mesh) {
  7030. this._engine = engine.getScene().getEngine();
  7031. } else {
  7032. this._engine = engine;
  7033. }
  7034. this._updatable = updatable;
  7035. this._data = data;
  7036. if (!postponeInternalCreation) {
  7037. this.create();
  7038. }
  7039. this._kind = kind;
  7040. switch (kind) {
  7041. case VertexBuffer.PositionKind:
  7042. this._strideSize = 3;
  7043. break;
  7044. case VertexBuffer.NormalKind:
  7045. this._strideSize = 3;
  7046. break;
  7047. case VertexBuffer.UVKind:
  7048. this._strideSize = 2;
  7049. break;
  7050. case VertexBuffer.UV2Kind:
  7051. this._strideSize = 2;
  7052. break;
  7053. case VertexBuffer.ColorKind:
  7054. this._strideSize = 3;
  7055. break;
  7056. case VertexBuffer.MatricesIndicesKind:
  7057. this._strideSize = 4;
  7058. break;
  7059. case VertexBuffer.MatricesWeightsKind:
  7060. this._strideSize = 4;
  7061. break;
  7062. }
  7063. }
  7064. VertexBuffer.prototype.isUpdatable = function () {
  7065. return this._updatable;
  7066. };
  7067. VertexBuffer.prototype.getData = function () {
  7068. return this._data;
  7069. };
  7070. VertexBuffer.prototype.getBuffer = function () {
  7071. return this._buffer;
  7072. };
  7073. VertexBuffer.prototype.getStrideSize = function () {
  7074. return this._strideSize;
  7075. };
  7076. VertexBuffer.prototype.create = function (data) {
  7077. if (!data && this._buffer) {
  7078. return;
  7079. }
  7080. data = data || this._data;
  7081. if (!this._buffer) {
  7082. if (this._updatable) {
  7083. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7084. } else {
  7085. this._buffer = this._engine.createVertexBuffer(data);
  7086. }
  7087. }
  7088. if (this._updatable) {
  7089. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7090. this._data = data;
  7091. }
  7092. };
  7093. VertexBuffer.prototype.update = function (data) {
  7094. this.create(data);
  7095. };
  7096. VertexBuffer.prototype.dispose = function () {
  7097. if (!this._buffer) {
  7098. return;
  7099. }
  7100. if (this._engine._releaseBuffer(this._buffer)) {
  7101. this._buffer = null;
  7102. }
  7103. };
  7104. Object.defineProperty(VertexBuffer, "PositionKind", {
  7105. get: function () {
  7106. return VertexBuffer._PositionKind;
  7107. },
  7108. enumerable: true,
  7109. configurable: true
  7110. });
  7111. Object.defineProperty(VertexBuffer, "NormalKind", {
  7112. get: function () {
  7113. return VertexBuffer._NormalKind;
  7114. },
  7115. enumerable: true,
  7116. configurable: true
  7117. });
  7118. Object.defineProperty(VertexBuffer, "UVKind", {
  7119. get: function () {
  7120. return VertexBuffer._UVKind;
  7121. },
  7122. enumerable: true,
  7123. configurable: true
  7124. });
  7125. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7126. get: function () {
  7127. return VertexBuffer._UV2Kind;
  7128. },
  7129. enumerable: true,
  7130. configurable: true
  7131. });
  7132. Object.defineProperty(VertexBuffer, "ColorKind", {
  7133. get: function () {
  7134. return VertexBuffer._ColorKind;
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7140. get: function () {
  7141. return VertexBuffer._MatricesIndicesKind;
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7147. get: function () {
  7148. return VertexBuffer._MatricesWeightsKind;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. VertexBuffer._PositionKind = "position";
  7154. VertexBuffer._NormalKind = "normal";
  7155. VertexBuffer._UVKind = "uv";
  7156. VertexBuffer._UV2Kind = "uv2";
  7157. VertexBuffer._ColorKind = "color";
  7158. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7159. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7160. return VertexBuffer;
  7161. })();
  7162. BABYLON.VertexBuffer = VertexBuffer;
  7163. })(BABYLON || (BABYLON = {}));
  7164. var __extends = this.__extends || function (d, b) {
  7165. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7166. function __() { this.constructor = d; }
  7167. __.prototype = b.prototype;
  7168. d.prototype = new __();
  7169. };
  7170. var BABYLON;
  7171. (function (BABYLON) {
  7172. var AbstractMesh = (function (_super) {
  7173. __extends(AbstractMesh, _super);
  7174. function AbstractMesh(name, scene) {
  7175. _super.call(this, name, scene);
  7176. this.position = new BABYLON.Vector3(0, 0, 0);
  7177. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7178. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7179. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7180. this.visibility = 1.0;
  7181. this.infiniteDistance = false;
  7182. this.isVisible = true;
  7183. this.isPickable = true;
  7184. this.showBoundingBox = false;
  7185. this.showSubMeshesBoundingBox = false;
  7186. this.onDispose = null;
  7187. this.checkCollisions = false;
  7188. this.isBlocker = false;
  7189. this.renderingGroupId = 0;
  7190. this.receiveShadows = false;
  7191. this.renderOutline = false;
  7192. this.outlineColor = BABYLON.Color3.Red();
  7193. this.outlineWidth = 0.02;
  7194. this.useOctreeForRenderingSelection = true;
  7195. this.useOctreeForPicking = true;
  7196. this.useOctreeForCollisions = true;
  7197. this.layerMask = 0xFFFFFFFF;
  7198. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7199. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7200. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7201. this._collider = new BABYLON.Collider();
  7202. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7203. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7204. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7205. this._localScaling = BABYLON.Matrix.Zero();
  7206. this._localRotation = BABYLON.Matrix.Zero();
  7207. this._localTranslation = BABYLON.Matrix.Zero();
  7208. this._localBillboard = BABYLON.Matrix.Zero();
  7209. this._localPivotScaling = BABYLON.Matrix.Zero();
  7210. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7211. this._localWorld = BABYLON.Matrix.Zero();
  7212. this._worldMatrix = BABYLON.Matrix.Zero();
  7213. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7214. this._absolutePosition = BABYLON.Vector3.Zero();
  7215. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7216. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7217. this._isDirty = false;
  7218. this._pivotMatrix = BABYLON.Matrix.Identity();
  7219. this._isDisposed = false;
  7220. this._renderId = 0;
  7221. this._intersectionsInProgress = new Array();
  7222. scene.meshes.push(this);
  7223. }
  7224. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7225. get: function () {
  7226. return AbstractMesh._BILLBOARDMODE_NONE;
  7227. },
  7228. enumerable: true,
  7229. configurable: true
  7230. });
  7231. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7232. get: function () {
  7233. return AbstractMesh._BILLBOARDMODE_X;
  7234. },
  7235. enumerable: true,
  7236. configurable: true
  7237. });
  7238. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7239. get: function () {
  7240. return AbstractMesh._BILLBOARDMODE_Y;
  7241. },
  7242. enumerable: true,
  7243. configurable: true
  7244. });
  7245. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7246. get: function () {
  7247. return AbstractMesh._BILLBOARDMODE_Z;
  7248. },
  7249. enumerable: true,
  7250. configurable: true
  7251. });
  7252. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7253. get: function () {
  7254. return AbstractMesh._BILLBOARDMODE_ALL;
  7255. },
  7256. enumerable: true,
  7257. configurable: true
  7258. });
  7259. AbstractMesh.prototype.getTotalVertices = function () {
  7260. return 0;
  7261. };
  7262. AbstractMesh.prototype.getIndices = function () {
  7263. return null;
  7264. };
  7265. AbstractMesh.prototype.getVerticesData = function (kind) {
  7266. return null;
  7267. };
  7268. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7269. return false;
  7270. };
  7271. AbstractMesh.prototype.getBoundingInfo = function () {
  7272. if (!this._boundingInfo) {
  7273. this._updateBoundingInfo();
  7274. }
  7275. return this._boundingInfo;
  7276. };
  7277. AbstractMesh.prototype._preActivate = function () {
  7278. };
  7279. AbstractMesh.prototype._activate = function (renderId) {
  7280. this._renderId = renderId;
  7281. };
  7282. AbstractMesh.prototype.getWorldMatrix = function () {
  7283. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7284. this.computeWorldMatrix();
  7285. }
  7286. return this._worldMatrix;
  7287. };
  7288. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7289. get: function () {
  7290. return this._worldMatrix;
  7291. },
  7292. enumerable: true,
  7293. configurable: true
  7294. });
  7295. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7296. get: function () {
  7297. return this._absolutePosition;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7303. if (!this.rotationQuaternion) {
  7304. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7305. this.rotation = BABYLON.Vector3.Zero();
  7306. }
  7307. if (!space || space == 0 /* LOCAL */) {
  7308. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7309. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7310. } else {
  7311. if (this.parent) {
  7312. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7313. invertParentWorldMatrix.invert();
  7314. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7315. }
  7316. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7317. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7318. }
  7319. };
  7320. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7321. var displacementVector = axis.scale(distance);
  7322. if (!space || space == 0 /* LOCAL */) {
  7323. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7324. this.setPositionWithLocalVector(tempV3);
  7325. } else {
  7326. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7327. }
  7328. };
  7329. AbstractMesh.prototype.getAbsolutePosition = function () {
  7330. this.computeWorldMatrix();
  7331. return this._absolutePosition;
  7332. };
  7333. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7334. if (!absolutePosition) {
  7335. return;
  7336. }
  7337. var absolutePositionX;
  7338. var absolutePositionY;
  7339. var absolutePositionZ;
  7340. if (absolutePosition.x === undefined) {
  7341. if (arguments.length < 3) {
  7342. return;
  7343. }
  7344. absolutePositionX = arguments[0];
  7345. absolutePositionY = arguments[1];
  7346. absolutePositionZ = arguments[2];
  7347. } else {
  7348. absolutePositionX = absolutePosition.x;
  7349. absolutePositionY = absolutePosition.y;
  7350. absolutePositionZ = absolutePosition.z;
  7351. }
  7352. if (this.parent) {
  7353. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7354. invertParentWorldMatrix.invert();
  7355. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7356. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7357. } else {
  7358. this.position.x = absolutePositionX;
  7359. this.position.y = absolutePositionY;
  7360. this.position.z = absolutePositionZ;
  7361. }
  7362. };
  7363. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7364. this._pivotMatrix = matrix;
  7365. this._cache.pivotMatrixUpdated = true;
  7366. };
  7367. AbstractMesh.prototype.getPivotMatrix = function () {
  7368. return this._pivotMatrix;
  7369. };
  7370. AbstractMesh.prototype._isSynchronized = function () {
  7371. if (this._isDirty) {
  7372. return false;
  7373. }
  7374. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7375. return false;
  7376. if (this._cache.pivotMatrixUpdated) {
  7377. return false;
  7378. }
  7379. if (this.infiniteDistance) {
  7380. return false;
  7381. }
  7382. if (!this._cache.position.equals(this.position))
  7383. return false;
  7384. if (this.rotationQuaternion) {
  7385. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7386. return false;
  7387. } else {
  7388. if (!this._cache.rotation.equals(this.rotation))
  7389. return false;
  7390. }
  7391. if (!this._cache.scaling.equals(this.scaling))
  7392. return false;
  7393. return true;
  7394. };
  7395. AbstractMesh.prototype._initCache = function () {
  7396. _super.prototype._initCache.call(this);
  7397. this._cache.localMatrixUpdated = false;
  7398. this._cache.position = BABYLON.Vector3.Zero();
  7399. this._cache.scaling = BABYLON.Vector3.Zero();
  7400. this._cache.rotation = BABYLON.Vector3.Zero();
  7401. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7402. };
  7403. AbstractMesh.prototype.markAsDirty = function (property) {
  7404. if (property === "rotation") {
  7405. this.rotationQuaternion = null;
  7406. }
  7407. this._currentRenderId = Number.MAX_VALUE;
  7408. this._isDirty = true;
  7409. };
  7410. AbstractMesh.prototype._updateBoundingInfo = function () {
  7411. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7412. this._boundingInfo._update(this.worldMatrixFromCache);
  7413. if (!this.subMeshes) {
  7414. return;
  7415. }
  7416. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7417. var subMesh = this.subMeshes[subIndex];
  7418. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7419. }
  7420. };
  7421. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7422. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7423. return this._worldMatrix;
  7424. }
  7425. this._cache.position.copyFrom(this.position);
  7426. this._cache.scaling.copyFrom(this.scaling);
  7427. this._cache.pivotMatrixUpdated = false;
  7428. this._currentRenderId = this.getScene().getRenderId();
  7429. this._isDirty = false;
  7430. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7431. if (this.rotationQuaternion) {
  7432. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7433. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7434. } else {
  7435. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7436. this._cache.rotation.copyFrom(this.rotation);
  7437. }
  7438. if (this.infiniteDistance && !this.parent) {
  7439. var camera = this.getScene().activeCamera;
  7440. var cameraWorldMatrix = camera.getWorldMatrix();
  7441. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7442. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7443. } else {
  7444. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7445. }
  7446. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7447. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7448. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7449. var localPosition = this.position.clone();
  7450. var zero = this.getScene().activeCamera.position.clone();
  7451. if (this.parent && this.parent.position) {
  7452. localPosition.addInPlace(this.parent.position);
  7453. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7454. }
  7455. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7456. zero = this.getScene().activeCamera.position;
  7457. } else {
  7458. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7459. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7460. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7461. zero.y = localPosition.y + 0.001;
  7462. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7463. zero.z = localPosition.z + 0.001;
  7464. }
  7465. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7466. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7467. this._localBillboard.invert();
  7468. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7469. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7470. }
  7471. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7472. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7473. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7474. } else {
  7475. this._worldMatrix.copyFrom(this._localWorld);
  7476. }
  7477. this._updateBoundingInfo();
  7478. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7479. return this._worldMatrix;
  7480. };
  7481. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7482. this.computeWorldMatrix();
  7483. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7484. };
  7485. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7486. this.computeWorldMatrix();
  7487. var invLocalWorldMatrix = this._localWorld.clone();
  7488. invLocalWorldMatrix.invert();
  7489. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7490. };
  7491. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7492. this.computeWorldMatrix();
  7493. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7494. };
  7495. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7496. yawCor = yawCor || 0;
  7497. pitchCor = pitchCor || 0;
  7498. rollCor = rollCor || 0;
  7499. var dv = targetPoint.subtract(this.position);
  7500. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7501. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7502. var pitch = Math.atan2(dv.y, len);
  7503. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7504. };
  7505. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7506. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7507. return false;
  7508. }
  7509. return true;
  7510. };
  7511. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7512. if (!this._boundingInfo || !mesh._boundingInfo) {
  7513. return false;
  7514. }
  7515. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7516. };
  7517. AbstractMesh.prototype.intersectsPoint = function (point) {
  7518. if (!this._boundingInfo) {
  7519. return false;
  7520. }
  7521. return this._boundingInfo.intersectsPoint(point);
  7522. };
  7523. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7524. var physicsEngine = this.getScene().getPhysicsEngine();
  7525. if (!physicsEngine) {
  7526. return;
  7527. }
  7528. if (impostor.impostor) {
  7529. options = impostor;
  7530. impostor = impostor.impostor;
  7531. }
  7532. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7533. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7534. physicsEngine._unregisterMesh(this);
  7535. return;
  7536. }
  7537. options.mass = options.mass || 0;
  7538. options.friction = options.friction || 0.2;
  7539. options.restitution = options.restitution || 0.9;
  7540. this._physicImpostor = impostor;
  7541. this._physicsMass = options.mass;
  7542. this._physicsFriction = options.friction;
  7543. this._physicRestitution = options.restitution;
  7544. physicsEngine._registerMesh(this, impostor, options);
  7545. };
  7546. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7547. if (!this._physicImpostor) {
  7548. return BABYLON.PhysicsEngine.NoImpostor;
  7549. }
  7550. return this._physicImpostor;
  7551. };
  7552. AbstractMesh.prototype.getPhysicsMass = function () {
  7553. if (!this._physicsMass) {
  7554. return 0;
  7555. }
  7556. return this._physicsMass;
  7557. };
  7558. AbstractMesh.prototype.getPhysicsFriction = function () {
  7559. if (!this._physicsFriction) {
  7560. return 0;
  7561. }
  7562. return this._physicsFriction;
  7563. };
  7564. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7565. if (!this._physicRestitution) {
  7566. return 0;
  7567. }
  7568. return this._physicRestitution;
  7569. };
  7570. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7571. if (!this._physicImpostor) {
  7572. return;
  7573. }
  7574. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7575. };
  7576. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7577. if (!this._physicImpostor) {
  7578. return;
  7579. }
  7580. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7581. };
  7582. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7583. if (!this._physicImpostor) {
  7584. return;
  7585. }
  7586. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7587. };
  7588. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7589. var globalPosition = this.getAbsolutePosition();
  7590. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7591. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7592. this._collider.radius = this.ellipsoid;
  7593. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7594. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7595. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7596. this.position.addInPlace(this._diffPositionForCollisions);
  7597. }
  7598. };
  7599. /**
  7600. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7601. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7602. */
  7603. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7604. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7605. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7606. if (!this._submeshesOctree) {
  7607. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7608. }
  7609. this.computeWorldMatrix(true);
  7610. var bbox = this.getBoundingInfo().boundingBox;
  7611. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7612. return this._submeshesOctree;
  7613. };
  7614. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7615. this._generatePointsArray();
  7616. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7617. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7618. subMesh._lastColliderWorldVertices = [];
  7619. subMesh._trianglePlanes = [];
  7620. var start = subMesh.verticesStart;
  7621. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7622. for (var i = start; i < end; i++) {
  7623. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7624. }
  7625. }
  7626. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7627. };
  7628. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7629. var subMeshes;
  7630. var len;
  7631. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7632. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7633. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7634. len = intersections.length;
  7635. subMeshes = intersections.data;
  7636. } else {
  7637. subMeshes = this.subMeshes;
  7638. len = subMeshes.length;
  7639. }
  7640. for (var index = 0; index < len; index++) {
  7641. var subMesh = subMeshes[index];
  7642. if (len > 1 && !subMesh._checkCollision(collider))
  7643. continue;
  7644. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7645. }
  7646. };
  7647. AbstractMesh.prototype._checkCollision = function (collider) {
  7648. if (!this._boundingInfo._checkCollision(collider))
  7649. return;
  7650. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7651. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7652. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7653. };
  7654. AbstractMesh.prototype._generatePointsArray = function () {
  7655. return false;
  7656. };
  7657. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7658. var pickingInfo = new BABYLON.PickingInfo();
  7659. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7660. return pickingInfo;
  7661. }
  7662. if (!this._generatePointsArray()) {
  7663. return pickingInfo;
  7664. }
  7665. var intersectInfo = null;
  7666. var subMeshes;
  7667. var len;
  7668. if (this._submeshesOctree && this.useOctreeForPicking) {
  7669. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7670. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7671. len = intersections.length;
  7672. subMeshes = intersections.data;
  7673. } else {
  7674. subMeshes = this.subMeshes;
  7675. len = subMeshes.length;
  7676. }
  7677. for (var index = 0; index < len; index++) {
  7678. var subMesh = subMeshes[index];
  7679. if (len > 1 && !subMesh.canIntersects(ray))
  7680. continue;
  7681. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7682. if (currentIntersectInfo) {
  7683. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7684. intersectInfo = currentIntersectInfo;
  7685. if (fastCheck) {
  7686. break;
  7687. }
  7688. }
  7689. }
  7690. }
  7691. if (intersectInfo) {
  7692. var world = this.getWorldMatrix();
  7693. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7694. var direction = ray.direction.clone();
  7695. direction.normalize();
  7696. direction = direction.scale(intersectInfo.distance);
  7697. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7698. var pickedPoint = worldOrigin.add(worldDirection);
  7699. pickingInfo.hit = true;
  7700. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7701. pickingInfo.pickedPoint = pickedPoint;
  7702. pickingInfo.pickedMesh = this;
  7703. pickingInfo.bu = intersectInfo.bu;
  7704. pickingInfo.bv = intersectInfo.bv;
  7705. pickingInfo.faceId = intersectInfo.faceId;
  7706. return pickingInfo;
  7707. }
  7708. return pickingInfo;
  7709. };
  7710. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7711. return null;
  7712. };
  7713. AbstractMesh.prototype.releaseSubMeshes = function () {
  7714. if (this.subMeshes) {
  7715. while (this.subMeshes.length) {
  7716. this.subMeshes[0].dispose();
  7717. }
  7718. } else {
  7719. this.subMeshes = new Array();
  7720. }
  7721. };
  7722. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7723. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7724. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7725. }
  7726. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7727. var other = this._intersectionsInProgress[index];
  7728. var pos = other._intersectionsInProgress.indexOf(this);
  7729. other._intersectionsInProgress.splice(pos, 1);
  7730. }
  7731. this._intersectionsInProgress = [];
  7732. this.releaseSubMeshes();
  7733. var index = this.getScene().meshes.indexOf(this);
  7734. if (index != -1) {
  7735. this.getScene().meshes.splice(index, 1);
  7736. }
  7737. if (!doNotRecurse) {
  7738. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7739. if (this.getScene().particleSystems[index].emitter == this) {
  7740. this.getScene().particleSystems[index].dispose();
  7741. index--;
  7742. }
  7743. }
  7744. var objects = this.getScene().meshes.slice(0);
  7745. for (index = 0; index < objects.length; index++) {
  7746. if (objects[index].parent == this) {
  7747. objects[index].dispose();
  7748. }
  7749. }
  7750. } else {
  7751. for (index = 0; index < this.getScene().meshes.length; index++) {
  7752. var obj = this.getScene().meshes[index];
  7753. if (obj.parent === this) {
  7754. obj.parent = null;
  7755. obj.computeWorldMatrix(true);
  7756. }
  7757. }
  7758. }
  7759. this._isDisposed = true;
  7760. if (this.onDispose) {
  7761. this.onDispose();
  7762. }
  7763. };
  7764. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7765. AbstractMesh._BILLBOARDMODE_X = 1;
  7766. AbstractMesh._BILLBOARDMODE_Y = 2;
  7767. AbstractMesh._BILLBOARDMODE_Z = 4;
  7768. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7769. return AbstractMesh;
  7770. })(BABYLON.Node);
  7771. BABYLON.AbstractMesh = AbstractMesh;
  7772. })(BABYLON || (BABYLON = {}));
  7773. var __extends = this.__extends || function (d, b) {
  7774. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7775. function __() { this.constructor = d; }
  7776. __.prototype = b.prototype;
  7777. d.prototype = new __();
  7778. };
  7779. var BABYLON;
  7780. (function (BABYLON) {
  7781. var _InstancesBatch = (function () {
  7782. function _InstancesBatch() {
  7783. this.mustReturn = false;
  7784. this.visibleInstances = new Array();
  7785. this.renderSelf = new Array();
  7786. }
  7787. return _InstancesBatch;
  7788. })();
  7789. BABYLON._InstancesBatch = _InstancesBatch;
  7790. var Mesh = (function (_super) {
  7791. __extends(Mesh, _super);
  7792. function Mesh(name, scene) {
  7793. _super.call(this, name, scene);
  7794. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7795. this.instances = new Array();
  7796. this._onBeforeRenderCallbacks = new Array();
  7797. this._onAfterRenderCallbacks = new Array();
  7798. this._visibleInstances = {};
  7799. this._renderIdForInstances = new Array();
  7800. this._batchCache = new _InstancesBatch();
  7801. this._instancesBufferSize = 32 * 16 * 4;
  7802. }
  7803. Mesh.prototype.getTotalVertices = function () {
  7804. if (!this._geometry) {
  7805. return 0;
  7806. }
  7807. return this._geometry.getTotalVertices();
  7808. };
  7809. Mesh.prototype.getVerticesData = function (kind) {
  7810. if (!this._geometry) {
  7811. return null;
  7812. }
  7813. return this._geometry.getVerticesData(kind);
  7814. };
  7815. Mesh.prototype.getVertexBuffer = function (kind) {
  7816. if (!this._geometry) {
  7817. return undefined;
  7818. }
  7819. return this._geometry.getVertexBuffer(kind);
  7820. };
  7821. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7822. if (!this._geometry) {
  7823. if (this._delayInfo) {
  7824. return this._delayInfo.indexOf(kind) !== -1;
  7825. }
  7826. return false;
  7827. }
  7828. return this._geometry.isVerticesDataPresent(kind);
  7829. };
  7830. Mesh.prototype.getVerticesDataKinds = function () {
  7831. if (!this._geometry) {
  7832. var result = [];
  7833. if (this._delayInfo) {
  7834. for (var kind in this._delayInfo) {
  7835. result.push(kind);
  7836. }
  7837. }
  7838. return result;
  7839. }
  7840. return this._geometry.getVerticesDataKinds();
  7841. };
  7842. Mesh.prototype.getTotalIndices = function () {
  7843. if (!this._geometry) {
  7844. return 0;
  7845. }
  7846. return this._geometry.getTotalIndices();
  7847. };
  7848. Mesh.prototype.getIndices = function () {
  7849. if (!this._geometry) {
  7850. return [];
  7851. }
  7852. return this._geometry.getIndices();
  7853. };
  7854. Mesh.prototype.isReady = function () {
  7855. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7856. return false;
  7857. }
  7858. return _super.prototype.isReady.call(this);
  7859. };
  7860. Mesh.prototype.isDisposed = function () {
  7861. return this._isDisposed;
  7862. };
  7863. Mesh.prototype._preActivate = function () {
  7864. var sceneRenderId = this.getScene().getRenderId();
  7865. if (this._preActivateId == sceneRenderId) {
  7866. return;
  7867. }
  7868. this._preActivateId = sceneRenderId;
  7869. this._visibleInstances = null;
  7870. };
  7871. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7872. if (!this._visibleInstances) {
  7873. this._visibleInstances = {};
  7874. this._visibleInstances.defaultRenderId = renderId;
  7875. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7876. }
  7877. if (!this._visibleInstances[renderId]) {
  7878. this._visibleInstances[renderId] = new Array();
  7879. }
  7880. this._visibleInstances[renderId].push(instance);
  7881. };
  7882. Mesh.prototype.refreshBoundingInfo = function () {
  7883. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7884. if (data) {
  7885. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7886. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7887. }
  7888. if (this.subMeshes) {
  7889. for (var index = 0; index < this.subMeshes.length; index++) {
  7890. this.subMeshes[index].refreshBoundingInfo();
  7891. }
  7892. }
  7893. this._updateBoundingInfo();
  7894. };
  7895. Mesh.prototype._createGlobalSubMesh = function () {
  7896. var totalVertices = this.getTotalVertices();
  7897. if (!totalVertices || !this.getIndices()) {
  7898. return null;
  7899. }
  7900. this.releaseSubMeshes();
  7901. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7902. };
  7903. Mesh.prototype.subdivide = function (count) {
  7904. if (count < 1) {
  7905. return;
  7906. }
  7907. var totalIndices = this.getTotalIndices();
  7908. var subdivisionSize = (totalIndices / count) | 0;
  7909. var offset = 0;
  7910. while (subdivisionSize % 3 != 0) {
  7911. subdivisionSize++;
  7912. }
  7913. this.releaseSubMeshes();
  7914. for (var index = 0; index < count; index++) {
  7915. if (offset >= totalIndices) {
  7916. break;
  7917. }
  7918. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7919. offset += subdivisionSize;
  7920. }
  7921. this.synchronizeInstances();
  7922. };
  7923. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7924. if (kind instanceof Array) {
  7925. var temp = data;
  7926. data = kind;
  7927. kind = temp;
  7928. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7929. }
  7930. if (!this._geometry) {
  7931. var vertexData = new BABYLON.VertexData();
  7932. vertexData.set(data, kind);
  7933. var scene = this.getScene();
  7934. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7935. } else {
  7936. this._geometry.setVerticesData(kind, data, updatable);
  7937. }
  7938. };
  7939. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7940. if (!this._geometry) {
  7941. return;
  7942. }
  7943. if (!makeItUnique) {
  7944. this._geometry.updateVerticesData(kind, data, updateExtends);
  7945. } else {
  7946. this.makeGeometryUnique();
  7947. this.updateVerticesData(kind, data, updateExtends, false);
  7948. }
  7949. };
  7950. Mesh.prototype.makeGeometryUnique = function () {
  7951. if (!this._geometry) {
  7952. return;
  7953. }
  7954. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7955. geometry.applyToMesh(this);
  7956. };
  7957. Mesh.prototype.setIndices = function (indices) {
  7958. if (!this._geometry) {
  7959. var vertexData = new BABYLON.VertexData();
  7960. vertexData.indices = indices;
  7961. var scene = this.getScene();
  7962. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7963. } else {
  7964. this._geometry.setIndices(indices);
  7965. }
  7966. };
  7967. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7968. var engine = this.getScene().getEngine();
  7969. var indexToBind = this._geometry.getIndexBuffer();
  7970. if (wireframe) {
  7971. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7972. }
  7973. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7974. };
  7975. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7976. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7977. return;
  7978. }
  7979. var engine = this.getScene().getEngine();
  7980. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7981. };
  7982. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7983. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7984. return;
  7985. }
  7986. var engine = this.getScene().getEngine();
  7987. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7988. };
  7989. Mesh.prototype.registerBeforeRender = function (func) {
  7990. this._onBeforeRenderCallbacks.push(func);
  7991. };
  7992. Mesh.prototype.unregisterBeforeRender = function (func) {
  7993. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7994. if (index > -1) {
  7995. this._onBeforeRenderCallbacks.splice(index, 1);
  7996. }
  7997. };
  7998. Mesh.prototype.registerAfterRender = function (func) {
  7999. this._onAfterRenderCallbacks.push(func);
  8000. };
  8001. Mesh.prototype.unregisterAfterRender = function (func) {
  8002. var index = this._onAfterRenderCallbacks.indexOf(func);
  8003. if (index > -1) {
  8004. this._onAfterRenderCallbacks.splice(index, 1);
  8005. }
  8006. };
  8007. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8008. var scene = this.getScene();
  8009. this._batchCache.mustReturn = false;
  8010. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8011. this._batchCache.visibleInstances[subMeshId] = null;
  8012. if (this._visibleInstances) {
  8013. var currentRenderId = scene.getRenderId();
  8014. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8015. var selfRenderId = this._renderId;
  8016. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8017. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8018. currentRenderId = this._visibleInstances.defaultRenderId;
  8019. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8020. }
  8021. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8022. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8023. this._batchCache.mustReturn = true;
  8024. return this._batchCache;
  8025. }
  8026. if (currentRenderId !== selfRenderId) {
  8027. this._batchCache.renderSelf[subMeshId] = false;
  8028. }
  8029. }
  8030. this._renderIdForInstances[subMeshId] = currentRenderId;
  8031. }
  8032. return this._batchCache;
  8033. };
  8034. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8035. var matricesCount = this.instances.length + 1;
  8036. var bufferSize = matricesCount * 16 * 4;
  8037. while (this._instancesBufferSize < bufferSize) {
  8038. this._instancesBufferSize *= 2;
  8039. }
  8040. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8041. if (this._worldMatricesInstancesBuffer) {
  8042. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8043. }
  8044. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8045. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8046. }
  8047. var offset = 0;
  8048. var instancesCount = 0;
  8049. var world = this.getWorldMatrix();
  8050. if (batch.renderSelf[subMesh._id]) {
  8051. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8052. offset += 16;
  8053. instancesCount++;
  8054. }
  8055. var visibleInstances = batch.visibleInstances[subMesh._id];
  8056. if (visibleInstances) {
  8057. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8058. var instance = visibleInstances[instanceIndex];
  8059. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8060. offset += 16;
  8061. instancesCount++;
  8062. }
  8063. }
  8064. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8065. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8066. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8067. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8068. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8069. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8070. this._draw(subMesh, !wireFrame, instancesCount);
  8071. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8072. };
  8073. Mesh.prototype.render = function (subMesh) {
  8074. var scene = this.getScene();
  8075. var batch = this._getInstancesRenderList(subMesh._id);
  8076. if (batch.mustReturn) {
  8077. return;
  8078. }
  8079. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8080. return;
  8081. }
  8082. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8083. this._onBeforeRenderCallbacks[callbackIndex]();
  8084. }
  8085. var engine = scene.getEngine();
  8086. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8087. var effectiveMaterial = subMesh.getMaterial();
  8088. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8089. return;
  8090. }
  8091. var savedDepthWrite = engine.getDepthWrite();
  8092. if (this.renderOutline) {
  8093. engine.setDepthWrite(false);
  8094. scene.getOutlineRenderer().render(subMesh, batch);
  8095. }
  8096. effectiveMaterial._preBind();
  8097. var effect = effectiveMaterial.getEffect();
  8098. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8099. this._bind(subMesh, effect, wireFrame);
  8100. var world = this.getWorldMatrix();
  8101. effectiveMaterial.bind(world, this);
  8102. if (hardwareInstancedRendering) {
  8103. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8104. } else {
  8105. if (batch.renderSelf[subMesh._id]) {
  8106. this._draw(subMesh, !wireFrame);
  8107. }
  8108. if (batch.visibleInstances[subMesh._id]) {
  8109. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8110. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8111. world = instance.getWorldMatrix();
  8112. effectiveMaterial.bindOnlyWorldMatrix(world);
  8113. this._draw(subMesh, !wireFrame);
  8114. }
  8115. }
  8116. }
  8117. effectiveMaterial.unbind();
  8118. if (this.renderOutline && savedDepthWrite) {
  8119. engine.setDepthWrite(true);
  8120. engine.setColorWrite(false);
  8121. scene.getOutlineRenderer().render(subMesh, batch);
  8122. engine.setColorWrite(true);
  8123. }
  8124. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8125. this._onAfterRenderCallbacks[callbackIndex]();
  8126. }
  8127. };
  8128. Mesh.prototype.getEmittedParticleSystems = function () {
  8129. var results = new Array();
  8130. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8131. var particleSystem = this.getScene().particleSystems[index];
  8132. if (particleSystem.emitter === this) {
  8133. results.push(particleSystem);
  8134. }
  8135. }
  8136. return results;
  8137. };
  8138. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8139. var results = new Array();
  8140. var descendants = this.getDescendants();
  8141. descendants.push(this);
  8142. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8143. var particleSystem = this.getScene().particleSystems[index];
  8144. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8145. results.push(particleSystem);
  8146. }
  8147. }
  8148. return results;
  8149. };
  8150. Mesh.prototype.getChildren = function () {
  8151. var results = [];
  8152. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8153. var mesh = this.getScene().meshes[index];
  8154. if (mesh.parent == this) {
  8155. results.push(mesh);
  8156. }
  8157. }
  8158. return results;
  8159. };
  8160. Mesh.prototype._checkDelayState = function () {
  8161. var _this = this;
  8162. var that = this;
  8163. var scene = this.getScene();
  8164. if (this._geometry) {
  8165. this._geometry.load(scene);
  8166. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8167. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8168. scene._addPendingData(that);
  8169. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8170. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8171. if (data instanceof ArrayBuffer) {
  8172. _this._delayLoadingFunction(data, _this);
  8173. } else {
  8174. _this._delayLoadingFunction(JSON.parse(data), _this);
  8175. }
  8176. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8177. scene._removePendingData(_this);
  8178. }, function () {
  8179. }, scene.database, getBinaryData);
  8180. }
  8181. };
  8182. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8183. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8184. return false;
  8185. }
  8186. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8187. return false;
  8188. }
  8189. this._checkDelayState();
  8190. return true;
  8191. };
  8192. Mesh.prototype.setMaterialByID = function (id) {
  8193. var materials = this.getScene().materials;
  8194. for (var index = 0; index < materials.length; index++) {
  8195. if (materials[index].id == id) {
  8196. this.material = materials[index];
  8197. return;
  8198. }
  8199. }
  8200. var multiMaterials = this.getScene().multiMaterials;
  8201. for (index = 0; index < multiMaterials.length; index++) {
  8202. if (multiMaterials[index].id == id) {
  8203. this.material = multiMaterials[index];
  8204. return;
  8205. }
  8206. }
  8207. };
  8208. Mesh.prototype.getAnimatables = function () {
  8209. var results = [];
  8210. if (this.material) {
  8211. results.push(this.material);
  8212. }
  8213. if (this.skeleton) {
  8214. results.push(this.skeleton);
  8215. }
  8216. return results;
  8217. };
  8218. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8219. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8220. return;
  8221. }
  8222. this._resetPointsArrayCache();
  8223. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8224. var temp = [];
  8225. for (var index = 0; index < data.length; index += 3) {
  8226. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8227. }
  8228. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8229. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8230. return;
  8231. }
  8232. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8233. for (index = 0; index < data.length; index += 3) {
  8234. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8235. }
  8236. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8237. };
  8238. Mesh.prototype._resetPointsArrayCache = function () {
  8239. this._positions = null;
  8240. };
  8241. Mesh.prototype._generatePointsArray = function () {
  8242. if (this._positions)
  8243. return true;
  8244. this._positions = [];
  8245. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8246. if (!data) {
  8247. return false;
  8248. }
  8249. for (var index = 0; index < data.length; index += 3) {
  8250. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8251. }
  8252. return true;
  8253. };
  8254. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8255. var result = new BABYLON.Mesh(name, this.getScene());
  8256. this._geometry.applyToMesh(result);
  8257. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8258. result.material = this.material;
  8259. if (newParent) {
  8260. result.parent = newParent;
  8261. }
  8262. if (!doNotCloneChildren) {
  8263. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8264. var mesh = this.getScene().meshes[index];
  8265. if (mesh.parent == this) {
  8266. mesh.clone(mesh.name, result);
  8267. }
  8268. }
  8269. }
  8270. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8271. var system = this.getScene().particleSystems[index];
  8272. if (system.emitter == this) {
  8273. system.clone(system.name, result);
  8274. }
  8275. }
  8276. result.computeWorldMatrix(true);
  8277. return result;
  8278. };
  8279. Mesh.prototype.dispose = function (doNotRecurse) {
  8280. if (this._geometry) {
  8281. this._geometry.releaseForMesh(this, true);
  8282. }
  8283. if (this._worldMatricesInstancesBuffer) {
  8284. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8285. this._worldMatricesInstancesBuffer = null;
  8286. }
  8287. while (this.instances.length) {
  8288. this.instances[0].dispose();
  8289. }
  8290. _super.prototype.dispose.call(this, doNotRecurse);
  8291. };
  8292. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8293. var _this = this;
  8294. var scene = this.getScene();
  8295. var onload = function (img) {
  8296. var canvas = document.createElement("canvas");
  8297. var context = canvas.getContext("2d");
  8298. var heightMapWidth = img.width;
  8299. var heightMapHeight = img.height;
  8300. canvas.width = heightMapWidth;
  8301. canvas.height = heightMapHeight;
  8302. context.drawImage(img, 0, 0);
  8303. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8304. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8305. };
  8306. BABYLON.Tools.LoadImage(url, onload, function () {
  8307. }, scene.database);
  8308. };
  8309. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8311. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8312. return;
  8313. }
  8314. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8315. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8316. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8317. var position = BABYLON.Vector3.Zero();
  8318. var normal = BABYLON.Vector3.Zero();
  8319. var uv = BABYLON.Vector2.Zero();
  8320. for (var index = 0; index < positions.length; index += 3) {
  8321. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8322. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8323. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8324. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8325. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8326. var pos = (u + v * heightMapWidth) * 4;
  8327. var r = buffer[pos] / 255.0;
  8328. var g = buffer[pos + 1] / 255.0;
  8329. var b = buffer[pos + 2] / 255.0;
  8330. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8331. normal.normalize();
  8332. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8333. position = position.add(normal);
  8334. position.toArray(positions, index);
  8335. }
  8336. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8337. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8338. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8339. };
  8340. Mesh.prototype.convertToFlatShadedMesh = function () {
  8341. var kinds = this.getVerticesDataKinds();
  8342. var vbs = [];
  8343. var data = [];
  8344. var newdata = [];
  8345. var updatableNormals = false;
  8346. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8347. var kind = kinds[kindIndex];
  8348. var vertexBuffer = this.getVertexBuffer(kind);
  8349. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8350. updatableNormals = vertexBuffer.isUpdatable();
  8351. kinds.splice(kindIndex, 1);
  8352. kindIndex--;
  8353. continue;
  8354. }
  8355. vbs[kind] = vertexBuffer;
  8356. data[kind] = vbs[kind].getData();
  8357. newdata[kind] = [];
  8358. }
  8359. var previousSubmeshes = this.subMeshes.slice(0);
  8360. var indices = this.getIndices();
  8361. var totalIndices = this.getTotalIndices();
  8362. for (index = 0; index < totalIndices; index++) {
  8363. var vertexIndex = indices[index];
  8364. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8365. kind = kinds[kindIndex];
  8366. var stride = vbs[kind].getStrideSize();
  8367. for (var offset = 0; offset < stride; offset++) {
  8368. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8369. }
  8370. }
  8371. }
  8372. var normals = [];
  8373. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8374. for (var index = 0; index < totalIndices; index += 3) {
  8375. indices[index] = index;
  8376. indices[index + 1] = index + 1;
  8377. indices[index + 2] = index + 2;
  8378. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8379. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8380. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8381. var p1p2 = p1.subtract(p2);
  8382. var p3p2 = p3.subtract(p2);
  8383. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8384. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8385. normals.push(normal.x);
  8386. normals.push(normal.y);
  8387. normals.push(normal.z);
  8388. }
  8389. }
  8390. this.setIndices(indices);
  8391. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8392. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8393. kind = kinds[kindIndex];
  8394. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8395. }
  8396. this.releaseSubMeshes();
  8397. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8398. var previousOne = previousSubmeshes[submeshIndex];
  8399. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8400. }
  8401. this.synchronizeInstances();
  8402. };
  8403. Mesh.prototype.createInstance = function (name) {
  8404. return new BABYLON.InstancedMesh(name, this);
  8405. };
  8406. Mesh.prototype.synchronizeInstances = function () {
  8407. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8408. var instance = this.instances[instanceIndex];
  8409. instance._syncSubMeshes();
  8410. }
  8411. };
  8412. Mesh.CreateBox = function (name, size, scene, updatable) {
  8413. var box = new BABYLON.Mesh(name, scene);
  8414. var vertexData = BABYLON.VertexData.CreateBox(size);
  8415. vertexData.applyToMesh(box, updatable);
  8416. return box;
  8417. };
  8418. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8419. var sphere = new BABYLON.Mesh(name, scene);
  8420. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8421. vertexData.applyToMesh(sphere, updatable);
  8422. return sphere;
  8423. };
  8424. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8425. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8426. if (scene !== undefined) {
  8427. updatable = scene;
  8428. }
  8429. scene = subdivisions;
  8430. subdivisions = 1;
  8431. }
  8432. var cylinder = new BABYLON.Mesh(name, scene);
  8433. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8434. vertexData.applyToMesh(cylinder, updatable);
  8435. return cylinder;
  8436. };
  8437. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8438. var torus = new BABYLON.Mesh(name, scene);
  8439. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8440. vertexData.applyToMesh(torus, updatable);
  8441. return torus;
  8442. };
  8443. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8444. var torusKnot = new BABYLON.Mesh(name, scene);
  8445. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8446. vertexData.applyToMesh(torusKnot, updatable);
  8447. return torusKnot;
  8448. };
  8449. Mesh.CreateLines = function (name, points, scene, updatable) {
  8450. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8451. var vertexData = BABYLON.VertexData.CreateLines(points);
  8452. vertexData.applyToMesh(lines, updatable);
  8453. return lines;
  8454. };
  8455. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8456. var plane = new BABYLON.Mesh(name, scene);
  8457. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8458. vertexData.applyToMesh(plane, updatable);
  8459. return plane;
  8460. };
  8461. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8462. var ground = new BABYLON.GroundMesh(name, scene);
  8463. ground._setReady(false);
  8464. ground._subdivisions = subdivisions;
  8465. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8466. vertexData.applyToMesh(ground, updatable);
  8467. ground._setReady(true);
  8468. return ground;
  8469. };
  8470. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8471. var tiledGround = new BABYLON.Mesh(name, scene);
  8472. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8473. vertexData.applyToMesh(tiledGround, updatable);
  8474. return tiledGround;
  8475. };
  8476. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8477. var ground = new BABYLON.GroundMesh(name, scene);
  8478. ground._subdivisions = subdivisions;
  8479. ground._setReady(false);
  8480. var onload = function (img) {
  8481. var canvas = document.createElement("canvas");
  8482. var context = canvas.getContext("2d");
  8483. var heightMapWidth = img.width;
  8484. var heightMapHeight = img.height;
  8485. canvas.width = heightMapWidth;
  8486. canvas.height = heightMapHeight;
  8487. context.drawImage(img, 0, 0);
  8488. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8489. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8490. vertexData.applyToMesh(ground, updatable);
  8491. ground._setReady(true);
  8492. };
  8493. BABYLON.Tools.LoadImage(url, onload, function () {
  8494. }, scene.database);
  8495. return ground;
  8496. };
  8497. Mesh.MinMax = function (meshes) {
  8498. var minVector = null;
  8499. var maxVector = null;
  8500. for (var i in meshes) {
  8501. var mesh = meshes[i];
  8502. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8503. if (!minVector) {
  8504. minVector = boundingBox.minimumWorld;
  8505. maxVector = boundingBox.maximumWorld;
  8506. continue;
  8507. }
  8508. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8509. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8510. }
  8511. return {
  8512. min: minVector,
  8513. max: maxVector
  8514. };
  8515. };
  8516. Mesh.Center = function (meshesOrMinMaxVector) {
  8517. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8518. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8519. };
  8520. return Mesh;
  8521. })(BABYLON.AbstractMesh);
  8522. BABYLON.Mesh = Mesh;
  8523. })(BABYLON || (BABYLON = {}));
  8524. var __extends = this.__extends || function (d, b) {
  8525. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8526. function __() { this.constructor = d; }
  8527. __.prototype = b.prototype;
  8528. d.prototype = new __();
  8529. };
  8530. var BABYLON;
  8531. (function (BABYLON) {
  8532. var GroundMesh = (function (_super) {
  8533. __extends(GroundMesh, _super);
  8534. function GroundMesh(name, scene) {
  8535. _super.call(this, name, scene);
  8536. this.generateOctree = false;
  8537. this._worldInverse = new BABYLON.Matrix();
  8538. }
  8539. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8540. get: function () {
  8541. return this._subdivisions;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. GroundMesh.prototype.optimize = function (chunksCount) {
  8547. this.subdivide(this._subdivisions);
  8548. this.createOrUpdateSubmeshesOctree(32);
  8549. };
  8550. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8551. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8552. this.getWorldMatrix().invertToRef(this._worldInverse);
  8553. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8554. var pickInfo = this.intersects(ray);
  8555. if (pickInfo.hit) {
  8556. return pickInfo.pickedPoint.y;
  8557. }
  8558. return 0;
  8559. };
  8560. return GroundMesh;
  8561. })(BABYLON.Mesh);
  8562. BABYLON.GroundMesh = GroundMesh;
  8563. })(BABYLON || (BABYLON = {}));
  8564. var __extends = this.__extends || function (d, b) {
  8565. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8566. function __() { this.constructor = d; }
  8567. __.prototype = b.prototype;
  8568. d.prototype = new __();
  8569. };
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. var InstancedMesh = (function (_super) {
  8573. __extends(InstancedMesh, _super);
  8574. function InstancedMesh(name, source) {
  8575. _super.call(this, name, source.getScene());
  8576. source.instances.push(this);
  8577. this._sourceMesh = source;
  8578. this.position.copyFrom(source.position);
  8579. this.rotation.copyFrom(source.rotation);
  8580. this.scaling.copyFrom(source.scaling);
  8581. if (source.rotationQuaternion) {
  8582. this.rotationQuaternion = source.rotationQuaternion.clone();
  8583. }
  8584. this.infiniteDistance = source.infiniteDistance;
  8585. this.setPivotMatrix(source.getPivotMatrix());
  8586. this.refreshBoundingInfo();
  8587. this._syncSubMeshes();
  8588. }
  8589. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8590. get: function () {
  8591. return this._sourceMesh.receiveShadows;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. Object.defineProperty(InstancedMesh.prototype, "material", {
  8597. get: function () {
  8598. return this._sourceMesh.material;
  8599. },
  8600. enumerable: true,
  8601. configurable: true
  8602. });
  8603. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8604. get: function () {
  8605. return this._sourceMesh.visibility;
  8606. },
  8607. enumerable: true,
  8608. configurable: true
  8609. });
  8610. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8611. get: function () {
  8612. return this._sourceMesh.skeleton;
  8613. },
  8614. enumerable: true,
  8615. configurable: true
  8616. });
  8617. InstancedMesh.prototype.getTotalVertices = function () {
  8618. return this._sourceMesh.getTotalVertices();
  8619. };
  8620. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8621. get: function () {
  8622. return this._sourceMesh;
  8623. },
  8624. enumerable: true,
  8625. configurable: true
  8626. });
  8627. InstancedMesh.prototype.getVerticesData = function (kind) {
  8628. return this._sourceMesh.getVerticesData(kind);
  8629. };
  8630. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8631. return this._sourceMesh.isVerticesDataPresent(kind);
  8632. };
  8633. InstancedMesh.prototype.getIndices = function () {
  8634. return this._sourceMesh.getIndices();
  8635. };
  8636. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8637. get: function () {
  8638. return this._sourceMesh._positions;
  8639. },
  8640. enumerable: true,
  8641. configurable: true
  8642. });
  8643. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8644. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8645. if (data) {
  8646. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8647. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8648. }
  8649. this._updateBoundingInfo();
  8650. };
  8651. InstancedMesh.prototype._preActivate = function () {
  8652. this.sourceMesh._preActivate();
  8653. };
  8654. InstancedMesh.prototype._activate = function (renderId) {
  8655. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8656. };
  8657. InstancedMesh.prototype._syncSubMeshes = function () {
  8658. this.releaseSubMeshes();
  8659. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8660. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8661. }
  8662. };
  8663. InstancedMesh.prototype._generatePointsArray = function () {
  8664. return this._sourceMesh._generatePointsArray();
  8665. };
  8666. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8667. var result = this._sourceMesh.createInstance(name);
  8668. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8669. this.refreshBoundingInfo();
  8670. if (newParent) {
  8671. result.parent = newParent;
  8672. }
  8673. if (!doNotCloneChildren) {
  8674. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8675. var mesh = this.getScene().meshes[index];
  8676. if (mesh.parent == this) {
  8677. mesh.clone(mesh.name, result);
  8678. }
  8679. }
  8680. }
  8681. result.computeWorldMatrix(true);
  8682. return result;
  8683. };
  8684. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8685. var index = this._sourceMesh.instances.indexOf(this);
  8686. this._sourceMesh.instances.splice(index, 1);
  8687. _super.prototype.dispose.call(this, doNotRecurse);
  8688. };
  8689. return InstancedMesh;
  8690. })(BABYLON.AbstractMesh);
  8691. BABYLON.InstancedMesh = InstancedMesh;
  8692. })(BABYLON || (BABYLON = {}));
  8693. var BABYLON;
  8694. (function (BABYLON) {
  8695. var SubMesh = (function () {
  8696. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8697. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8698. this.materialIndex = materialIndex;
  8699. this.verticesStart = verticesStart;
  8700. this.verticesCount = verticesCount;
  8701. this.indexStart = indexStart;
  8702. this.indexCount = indexCount;
  8703. this._renderId = 0;
  8704. this._mesh = mesh;
  8705. this._renderingMesh = renderingMesh || mesh;
  8706. mesh.subMeshes.push(this);
  8707. this._id = mesh.subMeshes.length - 1;
  8708. if (createBoundingBox) {
  8709. this.refreshBoundingInfo();
  8710. }
  8711. }
  8712. SubMesh.prototype.getBoundingInfo = function () {
  8713. return this._boundingInfo;
  8714. };
  8715. SubMesh.prototype.getMesh = function () {
  8716. return this._mesh;
  8717. };
  8718. SubMesh.prototype.getRenderingMesh = function () {
  8719. return this._renderingMesh;
  8720. };
  8721. SubMesh.prototype.getMaterial = function () {
  8722. var rootMaterial = this._renderingMesh.material;
  8723. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8724. var multiMaterial = rootMaterial;
  8725. return multiMaterial.getSubMaterial(this.materialIndex);
  8726. }
  8727. if (!rootMaterial) {
  8728. return this._mesh.getScene().defaultMaterial;
  8729. }
  8730. return rootMaterial;
  8731. };
  8732. SubMesh.prototype.refreshBoundingInfo = function () {
  8733. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8734. if (!data) {
  8735. this._boundingInfo = this._mesh._boundingInfo;
  8736. return;
  8737. }
  8738. var indices = this._renderingMesh.getIndices();
  8739. var extend;
  8740. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8741. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8742. } else {
  8743. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8744. }
  8745. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8746. };
  8747. SubMesh.prototype._checkCollision = function (collider) {
  8748. return this._boundingInfo._checkCollision(collider);
  8749. };
  8750. SubMesh.prototype.updateBoundingInfo = function (world) {
  8751. if (!this._boundingInfo) {
  8752. this.refreshBoundingInfo();
  8753. }
  8754. this._boundingInfo._update(world);
  8755. };
  8756. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8757. return this._boundingInfo.isInFrustum(frustumPlanes);
  8758. };
  8759. SubMesh.prototype.render = function () {
  8760. this._renderingMesh.render(this);
  8761. };
  8762. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8763. if (!this._linesIndexBuffer) {
  8764. var linesIndices = [];
  8765. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8766. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8767. }
  8768. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8769. this.linesIndexCount = linesIndices.length;
  8770. }
  8771. return this._linesIndexBuffer;
  8772. };
  8773. SubMesh.prototype.canIntersects = function (ray) {
  8774. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8775. };
  8776. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8777. var intersectInfo = null;
  8778. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8779. var p0 = positions[indices[index]];
  8780. var p1 = positions[indices[index + 1]];
  8781. var p2 = positions[indices[index + 2]];
  8782. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8783. if (currentIntersectInfo) {
  8784. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8785. intersectInfo = currentIntersectInfo;
  8786. intersectInfo.faceId = index / 3;
  8787. if (fastCheck) {
  8788. break;
  8789. }
  8790. }
  8791. }
  8792. }
  8793. return intersectInfo;
  8794. };
  8795. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8796. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8797. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8798. return result;
  8799. };
  8800. SubMesh.prototype.dispose = function () {
  8801. if (this._linesIndexBuffer) {
  8802. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8803. this._linesIndexBuffer = null;
  8804. }
  8805. var index = this._mesh.subMeshes.indexOf(this);
  8806. this._mesh.subMeshes.splice(index, 1);
  8807. };
  8808. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8809. var minVertexIndex = Number.MAX_VALUE;
  8810. var maxVertexIndex = -Number.MAX_VALUE;
  8811. renderingMesh = renderingMesh || mesh;
  8812. var indices = renderingMesh.getIndices();
  8813. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8814. var vertexIndex = indices[index];
  8815. if (vertexIndex < minVertexIndex)
  8816. minVertexIndex = vertexIndex;
  8817. if (vertexIndex > maxVertexIndex)
  8818. maxVertexIndex = vertexIndex;
  8819. }
  8820. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8821. };
  8822. return SubMesh;
  8823. })();
  8824. BABYLON.SubMesh = SubMesh;
  8825. })(BABYLON || (BABYLON = {}));
  8826. var BABYLON;
  8827. (function (BABYLON) {
  8828. var BaseTexture = (function () {
  8829. function BaseTexture(scene) {
  8830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8831. this.hasAlpha = false;
  8832. this.getAlphaFromRGB = false;
  8833. this.level = 1;
  8834. this.isCube = false;
  8835. this.isRenderTarget = false;
  8836. this.animations = new Array();
  8837. this.coordinatesIndex = 0;
  8838. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8839. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8840. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8841. this.anisotropicFilteringLevel = 4;
  8842. this._scene = scene;
  8843. this._scene.textures.push(this);
  8844. }
  8845. BaseTexture.prototype.getScene = function () {
  8846. return this._scene;
  8847. };
  8848. BaseTexture.prototype.getTextureMatrix = function () {
  8849. return null;
  8850. };
  8851. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8852. return null;
  8853. };
  8854. BaseTexture.prototype.getInternalTexture = function () {
  8855. return this._texture;
  8856. };
  8857. BaseTexture.prototype.isReady = function () {
  8858. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8859. return true;
  8860. }
  8861. if (this._texture) {
  8862. return this._texture.isReady;
  8863. }
  8864. return false;
  8865. };
  8866. BaseTexture.prototype.getSize = function () {
  8867. if (this._texture._width) {
  8868. return { width: this._texture._width, height: this._texture._height };
  8869. }
  8870. if (this._texture._size) {
  8871. return { width: this._texture._size, height: this._texture._size };
  8872. }
  8873. return { width: 0, height: 0 };
  8874. };
  8875. BaseTexture.prototype.getBaseSize = function () {
  8876. if (!this.isReady())
  8877. return { width: 0, height: 0 };
  8878. if (this._texture._size) {
  8879. return { width: this._texture._size, height: this._texture._size };
  8880. }
  8881. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8882. };
  8883. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8884. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8885. for (var index = 0; index < texturesCache.length; index++) {
  8886. var texturesCacheEntry = texturesCache[index];
  8887. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8888. texturesCacheEntry.references++;
  8889. return texturesCacheEntry;
  8890. }
  8891. }
  8892. return null;
  8893. };
  8894. BaseTexture.prototype.delayLoad = function () {
  8895. };
  8896. BaseTexture.prototype.releaseInternalTexture = function () {
  8897. if (!this._texture) {
  8898. return;
  8899. }
  8900. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8901. this._texture.references--;
  8902. if (this._texture.references == 0) {
  8903. var index = texturesCache.indexOf(this._texture);
  8904. texturesCache.splice(index, 1);
  8905. this._scene.getEngine()._releaseTexture(this._texture);
  8906. delete this._texture;
  8907. }
  8908. };
  8909. BaseTexture.prototype.clone = function () {
  8910. return null;
  8911. };
  8912. BaseTexture.prototype.dispose = function () {
  8913. var index = this._scene.textures.indexOf(this);
  8914. if (index >= 0) {
  8915. this._scene.textures.splice(index, 1);
  8916. }
  8917. if (this._texture === undefined) {
  8918. return;
  8919. }
  8920. this.releaseInternalTexture();
  8921. if (this.onDispose) {
  8922. this.onDispose();
  8923. }
  8924. };
  8925. return BaseTexture;
  8926. })();
  8927. BABYLON.BaseTexture = BaseTexture;
  8928. })(BABYLON || (BABYLON = {}));
  8929. var BABYLON;
  8930. (function (BABYLON) {
  8931. var RenderingGroup = (function () {
  8932. function RenderingGroup(index, scene) {
  8933. this.index = index;
  8934. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8935. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8936. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8937. this._scene = scene;
  8938. }
  8939. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8940. if (customRenderFunction) {
  8941. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8942. return true;
  8943. }
  8944. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8945. return false;
  8946. }
  8947. var engine = this._scene.getEngine();
  8948. var subIndex;
  8949. var submesh;
  8950. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8951. submesh = this._opaqueSubMeshes.data[subIndex];
  8952. this._activeVertices += submesh.verticesCount;
  8953. submesh.render();
  8954. }
  8955. engine.setAlphaTesting(true);
  8956. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8957. submesh = this._alphaTestSubMeshes.data[subIndex];
  8958. this._activeVertices += submesh.verticesCount;
  8959. submesh.render();
  8960. }
  8961. engine.setAlphaTesting(false);
  8962. if (beforeTransparents) {
  8963. beforeTransparents();
  8964. }
  8965. if (this._transparentSubMeshes.length) {
  8966. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8967. submesh = this._transparentSubMeshes.data[subIndex];
  8968. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8969. }
  8970. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8971. sortedArray.sort(function (a, b) {
  8972. if (a._distanceToCamera < b._distanceToCamera) {
  8973. return 1;
  8974. }
  8975. if (a._distanceToCamera > b._distanceToCamera) {
  8976. return -1;
  8977. }
  8978. return 0;
  8979. });
  8980. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8981. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8982. submesh = sortedArray[subIndex];
  8983. this._activeVertices += submesh.verticesCount;
  8984. submesh.render();
  8985. }
  8986. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8987. }
  8988. return true;
  8989. };
  8990. RenderingGroup.prototype.prepare = function () {
  8991. this._opaqueSubMeshes.reset();
  8992. this._transparentSubMeshes.reset();
  8993. this._alphaTestSubMeshes.reset();
  8994. };
  8995. RenderingGroup.prototype.dispatch = function (subMesh) {
  8996. var material = subMesh.getMaterial();
  8997. var mesh = subMesh.getMesh();
  8998. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8999. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9000. this._transparentSubMeshes.push(subMesh);
  9001. }
  9002. } else if (material.needAlphaTesting()) {
  9003. this._alphaTestSubMeshes.push(subMesh);
  9004. } else {
  9005. this._opaqueSubMeshes.push(subMesh);
  9006. }
  9007. };
  9008. return RenderingGroup;
  9009. })();
  9010. BABYLON.RenderingGroup = RenderingGroup;
  9011. })(BABYLON || (BABYLON = {}));
  9012. var BABYLON;
  9013. (function (BABYLON) {
  9014. var RenderingManager = (function () {
  9015. function RenderingManager(scene) {
  9016. this._renderingGroups = new Array();
  9017. this._scene = scene;
  9018. }
  9019. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9020. if (this._scene._activeParticleSystems.length === 0) {
  9021. return;
  9022. }
  9023. var beforeParticlesDate = new Date().getTime();
  9024. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9025. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9026. if (particleSystem.renderingGroupId !== index) {
  9027. continue;
  9028. }
  9029. this._clearDepthBuffer();
  9030. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9031. this._scene._activeParticles += particleSystem.render();
  9032. }
  9033. }
  9034. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  9035. };
  9036. RenderingManager.prototype._renderSprites = function (index) {
  9037. if (this._scene.spriteManagers.length === 0) {
  9038. return;
  9039. }
  9040. var beforeSpritessDate = new Date().getTime();
  9041. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9042. var spriteManager = this._scene.spriteManagers[id];
  9043. if (spriteManager.renderingGroupId === index) {
  9044. this._clearDepthBuffer();
  9045. spriteManager.render();
  9046. }
  9047. }
  9048. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  9049. };
  9050. RenderingManager.prototype._clearDepthBuffer = function () {
  9051. if (this._depthBufferAlreadyCleaned) {
  9052. return;
  9053. }
  9054. this._scene.getEngine().clear(0, false, true);
  9055. this._depthBufferAlreadyCleaned = true;
  9056. };
  9057. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9058. var _this = this;
  9059. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9060. this._depthBufferAlreadyCleaned = false;
  9061. var renderingGroup = this._renderingGroups[index];
  9062. if (renderingGroup) {
  9063. this._clearDepthBuffer();
  9064. if (!renderingGroup.render(customRenderFunction, function () {
  9065. if (renderSprites) {
  9066. _this._renderSprites(index);
  9067. }
  9068. })) {
  9069. this._renderingGroups.splice(index, 1);
  9070. }
  9071. } else if (renderSprites) {
  9072. this._renderSprites(index);
  9073. }
  9074. if (renderParticles) {
  9075. this._renderParticles(index, activeMeshes);
  9076. }
  9077. }
  9078. };
  9079. RenderingManager.prototype.reset = function () {
  9080. for (var index in this._renderingGroups) {
  9081. var renderingGroup = this._renderingGroups[index];
  9082. renderingGroup.prepare();
  9083. }
  9084. };
  9085. RenderingManager.prototype.dispatch = function (subMesh) {
  9086. var mesh = subMesh.getMesh();
  9087. var renderingGroupId = mesh.renderingGroupId || 0;
  9088. if (!this._renderingGroups[renderingGroupId]) {
  9089. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9090. }
  9091. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9092. };
  9093. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9094. return RenderingManager;
  9095. })();
  9096. BABYLON.RenderingManager = RenderingManager;
  9097. })(BABYLON || (BABYLON = {}));
  9098. var __extends = this.__extends || function (d, b) {
  9099. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9100. function __() { this.constructor = d; }
  9101. __.prototype = b.prototype;
  9102. d.prototype = new __();
  9103. };
  9104. var BABYLON;
  9105. (function (BABYLON) {
  9106. var Texture = (function (_super) {
  9107. __extends(Texture, _super);
  9108. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  9109. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9110. if (typeof onLoad === "undefined") { onLoad = null; }
  9111. if (typeof onError === "undefined") { onError = null; }
  9112. _super.call(this, scene);
  9113. this.uOffset = 0;
  9114. this.vOffset = 0;
  9115. this.uScale = 1.0;
  9116. this.vScale = 1.0;
  9117. this.uAng = 0;
  9118. this.vAng = 0;
  9119. this.wAng = 0;
  9120. this.name = url;
  9121. this.url = url;
  9122. this._noMipmap = noMipmap;
  9123. this._invertY = invertY;
  9124. this._samplingMode = samplingMode;
  9125. if (!url) {
  9126. return;
  9127. }
  9128. this._texture = this._getFromCache(url, noMipmap);
  9129. if (!this._texture) {
  9130. if (!scene.useDelayedTextureLoading) {
  9131. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError);
  9132. } else {
  9133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9134. }
  9135. }
  9136. }
  9137. Texture.prototype.delayLoad = function () {
  9138. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9139. return;
  9140. }
  9141. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9142. this._texture = this._getFromCache(this.url, this._noMipmap);
  9143. if (!this._texture) {
  9144. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9145. }
  9146. };
  9147. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9148. x -= this.uOffset + 0.5;
  9149. y -= this.vOffset + 0.5;
  9150. z -= 0.5;
  9151. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9152. t.x *= this.uScale;
  9153. t.y *= this.vScale;
  9154. t.x += 0.5;
  9155. t.y += 0.5;
  9156. t.z += 0.5;
  9157. };
  9158. Texture.prototype.getTextureMatrix = function () {
  9159. 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) {
  9160. return this._cachedTextureMatrix;
  9161. }
  9162. this._cachedUOffset = this.uOffset;
  9163. this._cachedVOffset = this.vOffset;
  9164. this._cachedUScale = this.uScale;
  9165. this._cachedVScale = this.vScale;
  9166. this._cachedUAng = this.uAng;
  9167. this._cachedVAng = this.vAng;
  9168. this._cachedWAng = this.wAng;
  9169. if (!this._cachedTextureMatrix) {
  9170. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9171. this._rowGenerationMatrix = new BABYLON.Matrix();
  9172. this._t0 = BABYLON.Vector3.Zero();
  9173. this._t1 = BABYLON.Vector3.Zero();
  9174. this._t2 = BABYLON.Vector3.Zero();
  9175. }
  9176. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9177. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9178. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9179. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9180. this._t1.subtractInPlace(this._t0);
  9181. this._t2.subtractInPlace(this._t0);
  9182. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9183. this._cachedTextureMatrix.m[0] = this._t1.x;
  9184. this._cachedTextureMatrix.m[1] = this._t1.y;
  9185. this._cachedTextureMatrix.m[2] = this._t1.z;
  9186. this._cachedTextureMatrix.m[4] = this._t2.x;
  9187. this._cachedTextureMatrix.m[5] = this._t2.y;
  9188. this._cachedTextureMatrix.m[6] = this._t2.z;
  9189. this._cachedTextureMatrix.m[8] = this._t0.x;
  9190. this._cachedTextureMatrix.m[9] = this._t0.y;
  9191. this._cachedTextureMatrix.m[10] = this._t0.z;
  9192. return this._cachedTextureMatrix;
  9193. };
  9194. Texture.prototype.getReflectionTextureMatrix = function () {
  9195. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9196. return this._cachedTextureMatrix;
  9197. }
  9198. if (!this._cachedTextureMatrix) {
  9199. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9200. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9201. }
  9202. switch (this.coordinatesMode) {
  9203. case BABYLON.Texture.SPHERICAL_MODE:
  9204. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9205. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9206. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9207. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9208. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9209. break;
  9210. case BABYLON.Texture.PLANAR_MODE:
  9211. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9212. this._cachedTextureMatrix[0] = this.uScale;
  9213. this._cachedTextureMatrix[5] = this.vScale;
  9214. this._cachedTextureMatrix[12] = this.uOffset;
  9215. this._cachedTextureMatrix[13] = this.vOffset;
  9216. break;
  9217. case BABYLON.Texture.PROJECTION_MODE:
  9218. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9219. this._projectionModeMatrix.m[0] = 0.5;
  9220. this._projectionModeMatrix.m[5] = -0.5;
  9221. this._projectionModeMatrix.m[10] = 0.0;
  9222. this._projectionModeMatrix.m[12] = 0.5;
  9223. this._projectionModeMatrix.m[13] = 0.5;
  9224. this._projectionModeMatrix.m[14] = 1.0;
  9225. this._projectionModeMatrix.m[15] = 1.0;
  9226. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9227. break;
  9228. default:
  9229. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9230. break;
  9231. }
  9232. return this._cachedTextureMatrix;
  9233. };
  9234. Texture.prototype.clone = function () {
  9235. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9236. newTexture.hasAlpha = this.hasAlpha;
  9237. newTexture.level = this.level;
  9238. newTexture.wrapU = this.wrapU;
  9239. newTexture.wrapV = this.wrapV;
  9240. newTexture.coordinatesIndex = this.coordinatesIndex;
  9241. newTexture.coordinatesMode = this.coordinatesMode;
  9242. newTexture.uOffset = this.uOffset;
  9243. newTexture.vOffset = this.vOffset;
  9244. newTexture.uScale = this.uScale;
  9245. newTexture.vScale = this.vScale;
  9246. newTexture.uAng = this.uAng;
  9247. newTexture.vAng = this.vAng;
  9248. newTexture.wAng = this.wAng;
  9249. return newTexture;
  9250. };
  9251. Texture.NEAREST_SAMPLINGMODE = 1;
  9252. Texture.BILINEAR_SAMPLINGMODE = 2;
  9253. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9254. Texture.EXPLICIT_MODE = 0;
  9255. Texture.SPHERICAL_MODE = 1;
  9256. Texture.PLANAR_MODE = 2;
  9257. Texture.CUBIC_MODE = 3;
  9258. Texture.PROJECTION_MODE = 4;
  9259. Texture.SKYBOX_MODE = 5;
  9260. Texture.CLAMP_ADDRESSMODE = 0;
  9261. Texture.WRAP_ADDRESSMODE = 1;
  9262. Texture.MIRROR_ADDRESSMODE = 2;
  9263. return Texture;
  9264. })(BABYLON.BaseTexture);
  9265. BABYLON.Texture = Texture;
  9266. })(BABYLON || (BABYLON = {}));
  9267. var __extends = this.__extends || function (d, b) {
  9268. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9269. function __() { this.constructor = d; }
  9270. __.prototype = b.prototype;
  9271. d.prototype = new __();
  9272. };
  9273. var BABYLON;
  9274. (function (BABYLON) {
  9275. var CubeTexture = (function (_super) {
  9276. __extends(CubeTexture, _super);
  9277. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9278. _super.call(this, scene);
  9279. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9280. this.name = rootUrl;
  9281. this.url = rootUrl;
  9282. this._noMipmap = noMipmap;
  9283. this.hasAlpha = false;
  9284. this._texture = this._getFromCache(rootUrl, noMipmap);
  9285. if (!extensions) {
  9286. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9287. }
  9288. this._extensions = extensions;
  9289. if (!this._texture) {
  9290. if (!scene.useDelayedTextureLoading) {
  9291. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9292. } else {
  9293. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9294. }
  9295. }
  9296. this.isCube = true;
  9297. this._textureMatrix = BABYLON.Matrix.Identity();
  9298. }
  9299. CubeTexture.prototype.clone = function () {
  9300. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9301. newTexture.level = this.level;
  9302. newTexture.wrapU = this.wrapU;
  9303. newTexture.wrapV = this.wrapV;
  9304. newTexture.coordinatesIndex = this.coordinatesIndex;
  9305. newTexture.coordinatesMode = this.coordinatesMode;
  9306. return newTexture;
  9307. };
  9308. CubeTexture.prototype.delayLoad = function () {
  9309. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9310. return;
  9311. }
  9312. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9313. this._texture = this._getFromCache(this.url, this._noMipmap);
  9314. if (!this._texture) {
  9315. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9316. }
  9317. };
  9318. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9319. return this._textureMatrix;
  9320. };
  9321. return CubeTexture;
  9322. })(BABYLON.BaseTexture);
  9323. BABYLON.CubeTexture = CubeTexture;
  9324. })(BABYLON || (BABYLON = {}));
  9325. var __extends = this.__extends || function (d, b) {
  9326. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9327. function __() { this.constructor = d; }
  9328. __.prototype = b.prototype;
  9329. d.prototype = new __();
  9330. };
  9331. var BABYLON;
  9332. (function (BABYLON) {
  9333. var RenderTargetTexture = (function (_super) {
  9334. __extends(RenderTargetTexture, _super);
  9335. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9336. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9337. _super.call(this, null, scene, !generateMipMaps);
  9338. this.renderList = new Array();
  9339. this.renderParticles = true;
  9340. this.renderSprites = false;
  9341. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9342. this._currentRefreshId = -1;
  9343. this._refreshRate = 1;
  9344. this.name = name;
  9345. this.isRenderTarget = true;
  9346. this._size = size;
  9347. this._generateMipMaps = generateMipMaps;
  9348. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9349. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9350. this._renderingManager = new BABYLON.RenderingManager(scene);
  9351. }
  9352. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9353. this._currentRefreshId = -1;
  9354. };
  9355. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9356. get: function () {
  9357. return this._refreshRate;
  9358. },
  9359. set: function (value) {
  9360. this._refreshRate = value;
  9361. this.resetRefreshCounter();
  9362. },
  9363. enumerable: true,
  9364. configurable: true
  9365. });
  9366. RenderTargetTexture.prototype._shouldRender = function () {
  9367. if (this._currentRefreshId === -1) {
  9368. this._currentRefreshId = 1;
  9369. return true;
  9370. }
  9371. if (this.refreshRate == this._currentRefreshId) {
  9372. this._currentRefreshId = 1;
  9373. return true;
  9374. }
  9375. this._currentRefreshId++;
  9376. return false;
  9377. };
  9378. RenderTargetTexture.prototype.getRenderSize = function () {
  9379. return this._size;
  9380. };
  9381. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9382. this.releaseInternalTexture();
  9383. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9384. };
  9385. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9386. var scene = this.getScene();
  9387. var engine = scene.getEngine();
  9388. if (this._waitingRenderList) {
  9389. this.renderList = [];
  9390. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9391. var id = this._waitingRenderList[index];
  9392. this.renderList.push(scene.getMeshByID(id));
  9393. }
  9394. delete this._waitingRenderList;
  9395. }
  9396. if (!this.renderList) {
  9397. return;
  9398. }
  9399. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9400. engine.bindFramebuffer(this._texture);
  9401. }
  9402. engine.clear(scene.clearColor, true, true);
  9403. this._renderingManager.reset();
  9404. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9405. var mesh = this.renderList[meshIndex];
  9406. if (mesh) {
  9407. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9408. this.resetRefreshCounter();
  9409. continue;
  9410. }
  9411. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9412. mesh._activate(scene.getRenderId());
  9413. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9414. var subMesh = mesh.subMeshes[subIndex];
  9415. scene._activeVertices += subMesh.verticesCount;
  9416. this._renderingManager.dispatch(subMesh);
  9417. }
  9418. }
  9419. }
  9420. }
  9421. if (!this._doNotChangeAspectRatio) {
  9422. scene.updateTransformMatrix(true);
  9423. }
  9424. if (this.onBeforeRender) {
  9425. this.onBeforeRender();
  9426. }
  9427. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9428. if (useCameraPostProcess) {
  9429. scene.postProcessManager._finalizeFrame(false, this._texture);
  9430. }
  9431. if (this.onAfterRender) {
  9432. this.onAfterRender();
  9433. }
  9434. engine.unBindFramebuffer(this._texture);
  9435. if (!this._doNotChangeAspectRatio) {
  9436. scene.updateTransformMatrix(true);
  9437. }
  9438. };
  9439. RenderTargetTexture.prototype.clone = function () {
  9440. var textureSize = this.getSize();
  9441. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9442. newTexture.hasAlpha = this.hasAlpha;
  9443. newTexture.level = this.level;
  9444. newTexture.coordinatesMode = this.coordinatesMode;
  9445. newTexture.renderList = this.renderList.slice(0);
  9446. return newTexture;
  9447. };
  9448. return RenderTargetTexture;
  9449. })(BABYLON.Texture);
  9450. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9451. })(BABYLON || (BABYLON = {}));
  9452. var __extends = this.__extends || function (d, b) {
  9453. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9454. function __() { this.constructor = d; }
  9455. __.prototype = b.prototype;
  9456. d.prototype = new __();
  9457. };
  9458. var BABYLON;
  9459. (function (BABYLON) {
  9460. var MirrorTexture = (function (_super) {
  9461. __extends(MirrorTexture, _super);
  9462. function MirrorTexture(name, size, scene, generateMipMaps) {
  9463. var _this = this;
  9464. _super.call(this, name, size, scene, generateMipMaps, true);
  9465. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9466. this._transformMatrix = BABYLON.Matrix.Zero();
  9467. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9468. this.onBeforeRender = function () {
  9469. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9470. _this._savedViewMatrix = scene.getViewMatrix();
  9471. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9472. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9473. scene.clipPlane = _this.mirrorPlane;
  9474. scene.getEngine().cullBackFaces = false;
  9475. };
  9476. this.onAfterRender = function () {
  9477. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9478. scene.getEngine().cullBackFaces = true;
  9479. delete scene.clipPlane;
  9480. };
  9481. }
  9482. MirrorTexture.prototype.clone = function () {
  9483. var textureSize = this.getSize();
  9484. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9485. newTexture.hasAlpha = this.hasAlpha;
  9486. newTexture.level = this.level;
  9487. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9488. newTexture.renderList = this.renderList.slice(0);
  9489. return newTexture;
  9490. };
  9491. return MirrorTexture;
  9492. })(BABYLON.RenderTargetTexture);
  9493. BABYLON.MirrorTexture = MirrorTexture;
  9494. })(BABYLON || (BABYLON = {}));
  9495. var __extends = this.__extends || function (d, b) {
  9496. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9497. function __() { this.constructor = d; }
  9498. __.prototype = b.prototype;
  9499. d.prototype = new __();
  9500. };
  9501. var BABYLON;
  9502. (function (BABYLON) {
  9503. var DynamicTexture = (function (_super) {
  9504. __extends(DynamicTexture, _super);
  9505. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9506. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9507. _super.call(this, null, scene, !generateMipMaps);
  9508. this.name = name;
  9509. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9510. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9511. this._generateMipMaps = generateMipMaps;
  9512. if (options.getContext) {
  9513. this._canvas = options;
  9514. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9515. } else {
  9516. this._canvas = document.createElement("canvas");
  9517. if (options.width) {
  9518. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9519. } else {
  9520. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9521. }
  9522. }
  9523. var textureSize = this.getSize();
  9524. this._canvas.width = textureSize.width;
  9525. this._canvas.height = textureSize.height;
  9526. this._context = this._canvas.getContext("2d");
  9527. }
  9528. DynamicTexture.prototype.getContext = function () {
  9529. return this._context;
  9530. };
  9531. DynamicTexture.prototype.update = function (invertY) {
  9532. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9533. };
  9534. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9535. var size = this.getSize();
  9536. if (clearColor) {
  9537. this._context.fillStyle = clearColor;
  9538. this._context.fillRect(0, 0, size.width, size.height);
  9539. }
  9540. this._context.font = font;
  9541. if (x === null) {
  9542. var textSize = this._context.measureText(text);
  9543. x = (size.width - textSize.width) / 2;
  9544. }
  9545. this._context.fillStyle = color;
  9546. this._context.fillText(text, x, y);
  9547. this.update(invertY);
  9548. };
  9549. DynamicTexture.prototype.clone = function () {
  9550. var textureSize = this.getSize();
  9551. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9552. newTexture.hasAlpha = this.hasAlpha;
  9553. newTexture.level = this.level;
  9554. newTexture.wrapU = this.wrapU;
  9555. newTexture.wrapV = this.wrapV;
  9556. return newTexture;
  9557. };
  9558. return DynamicTexture;
  9559. })(BABYLON.Texture);
  9560. BABYLON.DynamicTexture = DynamicTexture;
  9561. })(BABYLON || (BABYLON = {}));
  9562. var __extends = this.__extends || function (d, b) {
  9563. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9564. function __() { this.constructor = d; }
  9565. __.prototype = b.prototype;
  9566. d.prototype = new __();
  9567. };
  9568. var BABYLON;
  9569. (function (BABYLON) {
  9570. var VideoTexture = (function (_super) {
  9571. __extends(VideoTexture, _super);
  9572. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9573. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9574. var _this = this;
  9575. _super.call(this, null, scene, !generateMipMaps, invertY);
  9576. this._autoLaunch = true;
  9577. this.name = name;
  9578. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9579. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9580. var requiredWidth = size.width || size;
  9581. var requiredHeight = size.height || size;
  9582. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9583. var textureSize = this.getSize();
  9584. this.video = document.createElement("video");
  9585. this.video.width = textureSize.width;
  9586. this.video.height = textureSize.height;
  9587. this.video.autoplay = false;
  9588. this.video.loop = true;
  9589. this.video.addEventListener("canplaythrough", function () {
  9590. if (_this._texture) {
  9591. _this._texture.isReady = true;
  9592. }
  9593. });
  9594. urls.forEach(function (url) {
  9595. var source = document.createElement("source");
  9596. source.src = url;
  9597. _this.video.appendChild(source);
  9598. });
  9599. this._lastUpdate = new Date().getTime();
  9600. }
  9601. VideoTexture.prototype.update = function () {
  9602. if (this._autoLaunch) {
  9603. this._autoLaunch = false;
  9604. this.video.play();
  9605. }
  9606. var now = new Date().getTime();
  9607. if (now - this._lastUpdate < 15) {
  9608. return false;
  9609. }
  9610. this._lastUpdate = now;
  9611. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9612. return true;
  9613. };
  9614. return VideoTexture;
  9615. })(BABYLON.Texture);
  9616. BABYLON.VideoTexture = VideoTexture;
  9617. })(BABYLON || (BABYLON = {}));
  9618. var BABYLON;
  9619. (function (BABYLON) {
  9620. var EffectFallbacks = (function () {
  9621. function EffectFallbacks() {
  9622. this._defines = {};
  9623. this._currentRank = 32;
  9624. this._maxRank = -1;
  9625. }
  9626. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9627. if (!this._defines[rank]) {
  9628. if (rank < this._currentRank) {
  9629. this._currentRank = rank;
  9630. }
  9631. if (rank > this._maxRank) {
  9632. this._maxRank = rank;
  9633. }
  9634. this._defines[rank] = new Array();
  9635. }
  9636. this._defines[rank].push(define);
  9637. };
  9638. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9639. get: function () {
  9640. return this._currentRank <= this._maxRank;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9646. var currentFallbacks = this._defines[this._currentRank];
  9647. for (var index = 0; index < currentFallbacks.length; index++) {
  9648. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9649. }
  9650. this._currentRank++;
  9651. return currentDefines;
  9652. };
  9653. return EffectFallbacks;
  9654. })();
  9655. BABYLON.EffectFallbacks = EffectFallbacks;
  9656. var Effect = (function () {
  9657. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9658. var _this = this;
  9659. this._isReady = false;
  9660. this._compilationError = "";
  9661. this._valueCache = [];
  9662. this._engine = engine;
  9663. this.name = baseName;
  9664. this.defines = defines;
  9665. this._uniformsNames = uniformsNames.concat(samplers);
  9666. this._samplers = samplers;
  9667. this._attributesNames = attributesNames;
  9668. this.onError = onError;
  9669. this.onCompiled = onCompiled;
  9670. var vertexSource;
  9671. var fragmentSource;
  9672. if (baseName.vertexElement) {
  9673. vertexSource = document.getElementById(baseName.vertexElement);
  9674. if (!vertexSource) {
  9675. vertexSource = baseName.vertexElement;
  9676. }
  9677. } else {
  9678. vertexSource = baseName.vertex || baseName;
  9679. }
  9680. if (baseName.fragmentElement) {
  9681. fragmentSource = document.getElementById(baseName.fragmentElement);
  9682. if (!fragmentSource) {
  9683. fragmentSource = baseName.fragmentElement;
  9684. }
  9685. } else {
  9686. fragmentSource = baseName.fragment || baseName;
  9687. }
  9688. this._loadVertexShader(vertexSource, function (vertexCode) {
  9689. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9690. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9691. });
  9692. });
  9693. }
  9694. Effect.prototype.isReady = function () {
  9695. return this._isReady;
  9696. };
  9697. Effect.prototype.getProgram = function () {
  9698. return this._program;
  9699. };
  9700. Effect.prototype.getAttributesNames = function () {
  9701. return this._attributesNames;
  9702. };
  9703. Effect.prototype.getAttributeLocation = function (index) {
  9704. return this._attributes[index];
  9705. };
  9706. Effect.prototype.getAttributeLocationByName = function (name) {
  9707. var index = this._attributesNames.indexOf(name);
  9708. return this._attributes[index];
  9709. };
  9710. Effect.prototype.getAttributesCount = function () {
  9711. return this._attributes.length;
  9712. };
  9713. Effect.prototype.getUniformIndex = function (uniformName) {
  9714. return this._uniformsNames.indexOf(uniformName);
  9715. };
  9716. Effect.prototype.getUniform = function (uniformName) {
  9717. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9718. };
  9719. Effect.prototype.getSamplers = function () {
  9720. return this._samplers;
  9721. };
  9722. Effect.prototype.getCompilationError = function () {
  9723. return this._compilationError;
  9724. };
  9725. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9726. if (vertex instanceof HTMLElement) {
  9727. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9728. callback(vertexCode);
  9729. return;
  9730. }
  9731. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9732. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9733. return;
  9734. }
  9735. var vertexShaderUrl;
  9736. if (vertex[0] === ".") {
  9737. vertexShaderUrl = vertex;
  9738. } else {
  9739. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9740. }
  9741. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9742. };
  9743. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9744. if (fragment instanceof HTMLElement) {
  9745. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9746. callback(fragmentCode);
  9747. return;
  9748. }
  9749. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9750. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9751. return;
  9752. }
  9753. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  9754. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  9755. return;
  9756. }
  9757. var fragmentShaderUrl;
  9758. if (fragment[0] === ".") {
  9759. fragmentShaderUrl = fragment;
  9760. } else {
  9761. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9762. }
  9763. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9764. };
  9765. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9766. try {
  9767. var engine = this._engine;
  9768. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9770. this._attributes = engine.getAttributes(this._program, attributesNames);
  9771. for (var index = 0; index < this._samplers.length; index++) {
  9772. var sampler = this.getUniform(this._samplers[index]);
  9773. if (sampler == null) {
  9774. this._samplers.splice(index, 1);
  9775. index--;
  9776. }
  9777. }
  9778. engine.bindSamplers(this);
  9779. this._isReady = true;
  9780. if (this.onCompiled) {
  9781. this.onCompiled(this);
  9782. }
  9783. } catch (e) {
  9784. if (fallbacks && fallbacks.isMoreFallbacks) {
  9785. defines = fallbacks.reduce(defines);
  9786. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9787. } else {
  9788. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9789. BABYLON.Tools.Error("Defines: " + defines);
  9790. BABYLON.Tools.Error("Error: " + e.message);
  9791. this._compilationError = e.message;
  9792. if (this.onError) {
  9793. this.onError(this, this._compilationError);
  9794. }
  9795. }
  9796. }
  9797. };
  9798. Effect.prototype._bindTexture = function (channel, texture) {
  9799. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9800. };
  9801. Effect.prototype.setTexture = function (channel, texture) {
  9802. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9803. };
  9804. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9805. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9806. };
  9807. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9808. if (!this._valueCache[uniformName]) {
  9809. this._valueCache[uniformName] = [x, y];
  9810. return;
  9811. }
  9812. this._valueCache[uniformName][0] = x;
  9813. this._valueCache[uniformName][1] = y;
  9814. };
  9815. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9816. if (!this._valueCache[uniformName]) {
  9817. this._valueCache[uniformName] = [x, y, z];
  9818. return;
  9819. }
  9820. this._valueCache[uniformName][0] = x;
  9821. this._valueCache[uniformName][1] = y;
  9822. this._valueCache[uniformName][2] = z;
  9823. };
  9824. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9825. if (!this._valueCache[uniformName]) {
  9826. this._valueCache[uniformName] = [x, y, z, w];
  9827. return;
  9828. }
  9829. this._valueCache[uniformName][0] = x;
  9830. this._valueCache[uniformName][1] = y;
  9831. this._valueCache[uniformName][2] = z;
  9832. this._valueCache[uniformName][3] = w;
  9833. };
  9834. Effect.prototype.setArray = function (uniformName, array) {
  9835. this._engine.setArray(this.getUniform(uniformName), array);
  9836. return this;
  9837. };
  9838. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9839. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9840. return this;
  9841. };
  9842. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9843. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9844. return this;
  9845. };
  9846. Effect.prototype.setFloat = function (uniformName, value) {
  9847. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9848. return this;
  9849. this._valueCache[uniformName] = value;
  9850. this._engine.setFloat(this.getUniform(uniformName), value);
  9851. return this;
  9852. };
  9853. Effect.prototype.setBool = function (uniformName, bool) {
  9854. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9855. return this;
  9856. this._valueCache[uniformName] = bool;
  9857. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9858. return this;
  9859. };
  9860. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9861. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9862. return this;
  9863. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9864. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9865. return this;
  9866. };
  9867. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9868. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9869. return this;
  9870. this._cacheFloat2(uniformName, x, y);
  9871. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9872. return this;
  9873. };
  9874. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9875. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9876. return this;
  9877. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9878. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9879. return this;
  9880. };
  9881. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9882. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9883. return this;
  9884. this._cacheFloat3(uniformName, x, y, z);
  9885. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9886. return this;
  9887. };
  9888. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9889. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9890. return this;
  9891. this._cacheFloat4(uniformName, x, y, z, w);
  9892. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9893. return this;
  9894. };
  9895. Effect.prototype.setColor3 = function (uniformName, color3) {
  9896. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9897. return this;
  9898. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9899. this._engine.setColor3(this.getUniform(uniformName), color3);
  9900. return this;
  9901. };
  9902. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9903. 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)
  9904. return this;
  9905. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9906. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9907. return this;
  9908. };
  9909. 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}",
  9910. 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}",
  9911. 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}",
  9912. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9913. 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}",
  9914. 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}",
  9915. 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}",
  9916. 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}",
  9917. 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}",
  9918. 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}",
  9919. 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}",
  9920. 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}",
  9921. 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}",
  9922. 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}",
  9923. 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}",
  9924. 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}",
  9925. 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}",
  9926. 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}",
  9927. 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}",
  9928. 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}",
  9929. 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}",
  9930. 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}",
  9931. 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}",
  9932. 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}",
  9933. 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}",
  9934. 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}",
  9935. 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}",
  9936. 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}",
  9937. 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}",
  9938. };
  9939. return Effect;
  9940. })();
  9941. BABYLON.Effect = Effect;
  9942. })(BABYLON || (BABYLON = {}));
  9943. var BABYLON;
  9944. (function (BABYLON) {
  9945. var Material = (function () {
  9946. function Material(name, scene, doNotAdd) {
  9947. this.name = name;
  9948. this.checkReadyOnEveryCall = true;
  9949. this.checkReadyOnlyOnce = false;
  9950. this.state = "";
  9951. this.alpha = 1.0;
  9952. this.wireframe = false;
  9953. this.backFaceCulling = true;
  9954. this._wasPreviouslyReady = false;
  9955. this.id = name;
  9956. this._scene = scene;
  9957. if (!doNotAdd) {
  9958. scene.materials.push(this);
  9959. }
  9960. }
  9961. Material.prototype.isReady = function (mesh, useInstances) {
  9962. return true;
  9963. };
  9964. Material.prototype.getEffect = function () {
  9965. return this._effect;
  9966. };
  9967. Material.prototype.getScene = function () {
  9968. return this._scene;
  9969. };
  9970. Material.prototype.needAlphaBlending = function () {
  9971. return (this.alpha < 1.0);
  9972. };
  9973. Material.prototype.needAlphaTesting = function () {
  9974. return false;
  9975. };
  9976. Material.prototype.getAlphaTestTexture = function () {
  9977. return null;
  9978. };
  9979. Material.prototype.trackCreation = function (onCompiled, onError) {
  9980. };
  9981. Material.prototype._preBind = function () {
  9982. var engine = this._scene.getEngine();
  9983. engine.enableEffect(this._effect);
  9984. engine.setState(this.backFaceCulling);
  9985. };
  9986. Material.prototype.bind = function (world, mesh) {
  9987. };
  9988. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9989. };
  9990. Material.prototype.unbind = function () {
  9991. };
  9992. Material.prototype.dispose = function (forceDisposeEffect) {
  9993. var index = this._scene.materials.indexOf(this);
  9994. this._scene.materials.splice(index, 1);
  9995. if (forceDisposeEffect && this._effect) {
  9996. this._scene.getEngine()._releaseEffect(this._effect);
  9997. this._effect = null;
  9998. }
  9999. if (this.onDispose) {
  10000. this.onDispose();
  10001. }
  10002. };
  10003. return Material;
  10004. })();
  10005. BABYLON.Material = Material;
  10006. })(BABYLON || (BABYLON = {}));
  10007. var __extends = this.__extends || function (d, b) {
  10008. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10009. function __() { this.constructor = d; }
  10010. __.prototype = b.prototype;
  10011. d.prototype = new __();
  10012. };
  10013. var BABYLON;
  10014. (function (BABYLON) {
  10015. var maxSimultaneousLights = 4;
  10016. var FresnelParameters = (function () {
  10017. function FresnelParameters() {
  10018. this.isEnabled = true;
  10019. this.leftColor = BABYLON.Color3.White();
  10020. this.rightColor = BABYLON.Color3.Black();
  10021. this.bias = 0;
  10022. this.power = 1;
  10023. }
  10024. return FresnelParameters;
  10025. })();
  10026. BABYLON.FresnelParameters = FresnelParameters;
  10027. var StandardMaterial = (function (_super) {
  10028. __extends(StandardMaterial, _super);
  10029. function StandardMaterial(name, scene) {
  10030. var _this = this;
  10031. _super.call(this, name, scene);
  10032. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10033. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10034. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10035. this.specularPower = 64;
  10036. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10037. this.useAlphaFromDiffuseTexture = false;
  10038. this.useSpecularOverAlpha = true;
  10039. this._cachedDefines = null;
  10040. this._renderTargets = new BABYLON.SmartArray(16);
  10041. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10042. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10043. this._scaledDiffuse = new BABYLON.Color3();
  10044. this._scaledSpecular = new BABYLON.Color3();
  10045. this.getRenderTargetTextures = function () {
  10046. _this._renderTargets.reset();
  10047. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10048. _this._renderTargets.push(_this.reflectionTexture);
  10049. }
  10050. return _this._renderTargets;
  10051. };
  10052. }
  10053. StandardMaterial.prototype.needAlphaBlending = function () {
  10054. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10055. };
  10056. StandardMaterial.prototype.needAlphaTesting = function () {
  10057. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10058. };
  10059. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10060. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10061. };
  10062. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10063. return this.diffuseTexture;
  10064. };
  10065. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10066. if (this.checkReadyOnlyOnce) {
  10067. if (this._wasPreviouslyReady) {
  10068. return true;
  10069. }
  10070. }
  10071. var scene = this.getScene();
  10072. if (!this.checkReadyOnEveryCall) {
  10073. if (this._renderId === scene.getRenderId()) {
  10074. return true;
  10075. }
  10076. }
  10077. var engine = scene.getEngine();
  10078. var defines = [];
  10079. var fallbacks = new BABYLON.EffectFallbacks();
  10080. if (scene.texturesEnabled) {
  10081. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10082. if (!this.diffuseTexture.isReady()) {
  10083. return false;
  10084. } else {
  10085. defines.push("#define DIFFUSE");
  10086. }
  10087. }
  10088. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10089. if (!this.ambientTexture.isReady()) {
  10090. return false;
  10091. } else {
  10092. defines.push("#define AMBIENT");
  10093. }
  10094. }
  10095. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10096. if (!this.opacityTexture.isReady()) {
  10097. return false;
  10098. } else {
  10099. defines.push("#define OPACITY");
  10100. if (this.opacityTexture.getAlphaFromRGB) {
  10101. defines.push("#define OPACITYRGB");
  10102. }
  10103. }
  10104. }
  10105. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10106. if (!this.reflectionTexture.isReady()) {
  10107. return false;
  10108. } else {
  10109. defines.push("#define REFLECTION");
  10110. fallbacks.addFallback(0, "REFLECTION");
  10111. }
  10112. }
  10113. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10114. if (!this.emissiveTexture.isReady()) {
  10115. return false;
  10116. } else {
  10117. defines.push("#define EMISSIVE");
  10118. }
  10119. }
  10120. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10121. if (!this.specularTexture.isReady()) {
  10122. return false;
  10123. } else {
  10124. defines.push("#define SPECULAR");
  10125. fallbacks.addFallback(0, "SPECULAR");
  10126. }
  10127. }
  10128. }
  10129. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10130. if (!this.bumpTexture.isReady()) {
  10131. return false;
  10132. } else {
  10133. defines.push("#define BUMP");
  10134. fallbacks.addFallback(0, "BUMP");
  10135. }
  10136. }
  10137. if (this.useSpecularOverAlpha) {
  10138. defines.push("#define SPECULAROVERALPHA");
  10139. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10140. }
  10141. if (scene.clipPlane) {
  10142. defines.push("#define CLIPPLANE");
  10143. }
  10144. if (engine.getAlphaTesting()) {
  10145. defines.push("#define ALPHATEST");
  10146. }
  10147. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10148. defines.push("#define ALPHAFROMDIFFUSE");
  10149. }
  10150. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10151. defines.push("#define FOG");
  10152. fallbacks.addFallback(1, "FOG");
  10153. }
  10154. var shadowsActivated = false;
  10155. var lightIndex = 0;
  10156. if (scene.lightsEnabled) {
  10157. for (var index = 0; index < scene.lights.length; index++) {
  10158. var light = scene.lights[index];
  10159. if (!light.isEnabled()) {
  10160. continue;
  10161. }
  10162. if (light._excludedMeshesIds.length > 0) {
  10163. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10164. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10165. if (excludedMesh) {
  10166. light.excludedMeshes.push(excludedMesh);
  10167. }
  10168. }
  10169. light._excludedMeshesIds = [];
  10170. }
  10171. if (light._includedOnlyMeshesIds.length > 0) {
  10172. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10173. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10174. if (includedOnlyMesh) {
  10175. light.includedOnlyMeshes.push(includedOnlyMesh);
  10176. }
  10177. }
  10178. light._includedOnlyMeshesIds = [];
  10179. }
  10180. if (!light.canAffectMesh(mesh)) {
  10181. continue;
  10182. }
  10183. defines.push("#define LIGHT" + lightIndex);
  10184. if (lightIndex > 0) {
  10185. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10186. }
  10187. var type;
  10188. if (light instanceof BABYLON.SpotLight) {
  10189. type = "#define SPOTLIGHT" + lightIndex;
  10190. } else if (light instanceof BABYLON.HemisphericLight) {
  10191. type = "#define HEMILIGHT" + lightIndex;
  10192. } else {
  10193. type = "#define POINTDIRLIGHT" + lightIndex;
  10194. }
  10195. defines.push(type);
  10196. if (lightIndex > 0) {
  10197. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10198. }
  10199. var shadowGenerator = light.getShadowGenerator();
  10200. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10201. defines.push("#define SHADOW" + lightIndex);
  10202. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10203. if (!shadowsActivated) {
  10204. defines.push("#define SHADOWS");
  10205. shadowsActivated = true;
  10206. }
  10207. if (shadowGenerator.useVarianceShadowMap) {
  10208. defines.push("#define SHADOWVSM" + lightIndex);
  10209. if (lightIndex > 0) {
  10210. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10211. }
  10212. }
  10213. if (shadowGenerator.usePoissonSampling) {
  10214. defines.push("#define SHADOWPCF" + lightIndex);
  10215. if (lightIndex > 0) {
  10216. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10217. }
  10218. }
  10219. }
  10220. lightIndex++;
  10221. if (lightIndex == maxSimultaneousLights)
  10222. break;
  10223. }
  10224. }
  10225. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10226. var fresnelRank = 1;
  10227. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10228. defines.push("#define DIFFUSEFRESNEL");
  10229. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10230. fresnelRank++;
  10231. }
  10232. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10233. defines.push("#define OPACITYFRESNEL");
  10234. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10235. fresnelRank++;
  10236. }
  10237. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10238. defines.push("#define REFLECTIONFRESNEL");
  10239. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10240. fresnelRank++;
  10241. }
  10242. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10243. defines.push("#define EMISSIVEFRESNEL");
  10244. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10245. fresnelRank++;
  10246. }
  10247. defines.push("#define FRESNEL");
  10248. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10249. }
  10250. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10251. if (mesh) {
  10252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10253. attribs.push(BABYLON.VertexBuffer.UVKind);
  10254. defines.push("#define UV1");
  10255. }
  10256. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10257. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10258. defines.push("#define UV2");
  10259. }
  10260. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10261. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10262. defines.push("#define VERTEXCOLOR");
  10263. }
  10264. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10267. defines.push("#define BONES");
  10268. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10269. defines.push("#define BONES4");
  10270. fallbacks.addFallback(0, "BONES4");
  10271. }
  10272. if (useInstances) {
  10273. defines.push("#define INSTANCES");
  10274. attribs.push("world0");
  10275. attribs.push("world1");
  10276. attribs.push("world2");
  10277. attribs.push("world3");
  10278. }
  10279. }
  10280. var join = defines.join("\n");
  10281. if (this._cachedDefines != join) {
  10282. this._cachedDefines = join;
  10283. var shaderName = "default";
  10284. if (!scene.getEngine().getCaps().standardDerivatives) {
  10285. shaderName = "legacydefault";
  10286. }
  10287. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10288. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10289. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10290. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10291. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10292. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10293. "vFogInfos", "vFogColor",
  10294. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10295. "mBones",
  10296. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10297. "darkness0", "darkness1", "darkness2", "darkness3",
  10298. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10299. ], [
  10300. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10301. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10302. ], join, fallbacks, this.onCompiled, this.onError);
  10303. }
  10304. if (!this._effect.isReady()) {
  10305. return false;
  10306. }
  10307. this._renderId = scene.getRenderId();
  10308. this._wasPreviouslyReady = true;
  10309. return true;
  10310. };
  10311. StandardMaterial.prototype.unbind = function () {
  10312. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10313. this._effect.setTexture("reflection2DSampler", null);
  10314. }
  10315. };
  10316. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10317. this._effect.setMatrix("world", world);
  10318. };
  10319. StandardMaterial.prototype.bind = function (world, mesh) {
  10320. var scene = this.getScene();
  10321. this.bindOnlyWorldMatrix(world);
  10322. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10323. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10324. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10325. }
  10326. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10327. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10328. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10329. }
  10330. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10331. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10332. }
  10333. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10334. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10335. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10336. }
  10337. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10338. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10339. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10340. }
  10341. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10342. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10343. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10344. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10345. }
  10346. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10347. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10348. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10349. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10350. }
  10351. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10352. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10353. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10354. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10355. }
  10356. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10357. if (this.reflectionTexture.isCube) {
  10358. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10359. } else {
  10360. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10361. }
  10362. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10363. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10364. }
  10365. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10366. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10367. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10368. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10369. }
  10370. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10371. this._effect.setTexture("specularSampler", this.specularTexture);
  10372. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10373. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10374. }
  10375. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10376. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10377. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10378. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10379. }
  10380. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10381. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10382. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10383. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10384. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10385. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10386. if (scene.lightsEnabled) {
  10387. var lightIndex = 0;
  10388. for (var index = 0; index < scene.lights.length; index++) {
  10389. var light = scene.lights[index];
  10390. if (!light.isEnabled()) {
  10391. continue;
  10392. }
  10393. if (!light.canAffectMesh(mesh)) {
  10394. continue;
  10395. }
  10396. if (light instanceof BABYLON.PointLight) {
  10397. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10398. } else if (light instanceof BABYLON.DirectionalLight) {
  10399. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10400. } else if (light instanceof BABYLON.SpotLight) {
  10401. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10402. } else if (light instanceof BABYLON.HemisphericLight) {
  10403. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10404. }
  10405. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10406. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10407. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10408. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10409. var shadowGenerator = light.getShadowGenerator();
  10410. if (mesh.receiveShadows && shadowGenerator) {
  10411. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10412. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10413. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10414. }
  10415. lightIndex++;
  10416. if (lightIndex == maxSimultaneousLights)
  10417. break;
  10418. }
  10419. }
  10420. if (scene.clipPlane) {
  10421. var clipPlane = scene.clipPlane;
  10422. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10423. }
  10424. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10425. this._effect.setMatrix("view", scene.getViewMatrix());
  10426. }
  10427. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10428. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10429. this._effect.setColor3("vFogColor", scene.fogColor);
  10430. }
  10431. };
  10432. StandardMaterial.prototype.getAnimatables = function () {
  10433. var results = [];
  10434. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10435. results.push(this.diffuseTexture);
  10436. }
  10437. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10438. results.push(this.ambientTexture);
  10439. }
  10440. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10441. results.push(this.opacityTexture);
  10442. }
  10443. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10444. results.push(this.reflectionTexture);
  10445. }
  10446. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10447. results.push(this.emissiveTexture);
  10448. }
  10449. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10450. results.push(this.specularTexture);
  10451. }
  10452. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10453. results.push(this.bumpTexture);
  10454. }
  10455. return results;
  10456. };
  10457. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10458. if (this.diffuseTexture) {
  10459. this.diffuseTexture.dispose();
  10460. }
  10461. if (this.ambientTexture) {
  10462. this.ambientTexture.dispose();
  10463. }
  10464. if (this.opacityTexture) {
  10465. this.opacityTexture.dispose();
  10466. }
  10467. if (this.reflectionTexture) {
  10468. this.reflectionTexture.dispose();
  10469. }
  10470. if (this.emissiveTexture) {
  10471. this.emissiveTexture.dispose();
  10472. }
  10473. if (this.specularTexture) {
  10474. this.specularTexture.dispose();
  10475. }
  10476. if (this.bumpTexture) {
  10477. this.bumpTexture.dispose();
  10478. }
  10479. _super.prototype.dispose.call(this, forceDisposeEffect);
  10480. };
  10481. StandardMaterial.prototype.clone = function (name) {
  10482. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10483. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10484. newStandardMaterial.alpha = this.alpha;
  10485. newStandardMaterial.wireframe = this.wireframe;
  10486. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10487. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10488. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10489. }
  10490. if (this.ambientTexture && this.ambientTexture.clone) {
  10491. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10492. }
  10493. if (this.opacityTexture && this.opacityTexture.clone) {
  10494. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10495. }
  10496. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10497. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10498. }
  10499. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10500. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10501. }
  10502. if (this.specularTexture && this.specularTexture.clone) {
  10503. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10504. }
  10505. if (this.bumpTexture && this.bumpTexture.clone) {
  10506. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10507. }
  10508. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10509. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10510. newStandardMaterial.specularColor = this.specularColor.clone();
  10511. newStandardMaterial.specularPower = this.specularPower;
  10512. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10513. return newStandardMaterial;
  10514. };
  10515. StandardMaterial.DiffuseTextureEnabled = true;
  10516. StandardMaterial.AmbientTextureEnabled = true;
  10517. StandardMaterial.OpacityTextureEnabled = true;
  10518. StandardMaterial.ReflectionTextureEnabled = true;
  10519. StandardMaterial.EmissiveTextureEnabled = true;
  10520. StandardMaterial.SpecularTextureEnabled = true;
  10521. StandardMaterial.BumpTextureEnabled = true;
  10522. return StandardMaterial;
  10523. })(BABYLON.Material);
  10524. BABYLON.StandardMaterial = StandardMaterial;
  10525. })(BABYLON || (BABYLON = {}));
  10526. var __extends = this.__extends || function (d, b) {
  10527. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10528. function __() { this.constructor = d; }
  10529. __.prototype = b.prototype;
  10530. d.prototype = new __();
  10531. };
  10532. var BABYLON;
  10533. (function (BABYLON) {
  10534. var MultiMaterial = (function (_super) {
  10535. __extends(MultiMaterial, _super);
  10536. function MultiMaterial(name, scene) {
  10537. _super.call(this, name, scene, true);
  10538. this.subMaterials = new Array();
  10539. scene.multiMaterials.push(this);
  10540. }
  10541. MultiMaterial.prototype.getSubMaterial = function (index) {
  10542. if (index < 0 || index >= this.subMaterials.length) {
  10543. return this.getScene().defaultMaterial;
  10544. }
  10545. return this.subMaterials[index];
  10546. };
  10547. MultiMaterial.prototype.isReady = function (mesh) {
  10548. for (var index = 0; index < this.subMaterials.length; index++) {
  10549. var subMaterial = this.subMaterials[index];
  10550. if (subMaterial) {
  10551. if (!this.subMaterials[index].isReady(mesh)) {
  10552. return false;
  10553. }
  10554. }
  10555. }
  10556. return true;
  10557. };
  10558. return MultiMaterial;
  10559. })(BABYLON.Material);
  10560. BABYLON.MultiMaterial = MultiMaterial;
  10561. })(BABYLON || (BABYLON = {}));
  10562. var BABYLON;
  10563. (function (BABYLON) {
  10564. var Database = (function () {
  10565. function Database(urlToScene, callbackManifestChecked) {
  10566. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10567. this.callbackManifestChecked = callbackManifestChecked;
  10568. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10569. this.db = null;
  10570. this.enableSceneOffline = false;
  10571. this.enableTexturesOffline = false;
  10572. this.manifestVersionFound = 0;
  10573. this.mustUpdateRessources = false;
  10574. this.hasReachedQuota = false;
  10575. this.checkManifestFile();
  10576. }
  10577. Database.prototype.checkManifestFile = function () {
  10578. var _this = this;
  10579. function noManifestFile() {
  10580. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10581. that.enableSceneOffline = false;
  10582. that.enableTexturesOffline = false;
  10583. that.callbackManifestChecked(false);
  10584. }
  10585. var that = this;
  10586. var manifestURL = this.currentSceneUrl + ".manifest";
  10587. var xhr = new XMLHttpRequest();
  10588. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10589. xhr.open("GET", manifestURLTimeStamped, true);
  10590. xhr.addEventListener("load", function () {
  10591. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10592. try {
  10593. var manifestFile = JSON.parse(xhr.response);
  10594. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10595. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10596. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10597. _this.manifestVersionFound = manifestFile.version;
  10598. }
  10599. if (_this.callbackManifestChecked) {
  10600. _this.callbackManifestChecked(true);
  10601. }
  10602. } catch (ex) {
  10603. noManifestFile();
  10604. }
  10605. } else {
  10606. noManifestFile();
  10607. }
  10608. }, false);
  10609. xhr.addEventListener("error", function (event) {
  10610. noManifestFile();
  10611. }, false);
  10612. try {
  10613. xhr.send();
  10614. } catch (ex) {
  10615. BABYLON.Tools.Error("Error on XHR send request.");
  10616. that.callbackManifestChecked(false);
  10617. }
  10618. };
  10619. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10620. var _this = this;
  10621. function handleError() {
  10622. that.isSupported = false;
  10623. if (errorCallback)
  10624. errorCallback();
  10625. }
  10626. var that = this;
  10627. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10628. this.isSupported = false;
  10629. if (errorCallback)
  10630. errorCallback();
  10631. } else {
  10632. if (!this.db) {
  10633. this.hasReachedQuota = false;
  10634. this.isSupported = true;
  10635. var request = this.idbFactory.open("babylonjs", 1);
  10636. request.onerror = function (event) {
  10637. handleError();
  10638. };
  10639. request.onblocked = function (event) {
  10640. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10641. handleError();
  10642. };
  10643. request.onsuccess = function (event) {
  10644. _this.db = request.result;
  10645. successCallback();
  10646. };
  10647. request.onupgradeneeded = function (event) {
  10648. _this.db = (event.target).result;
  10649. try {
  10650. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10651. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10652. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10653. } catch (ex) {
  10654. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10655. handleError();
  10656. }
  10657. };
  10658. } else {
  10659. if (successCallback)
  10660. successCallback();
  10661. }
  10662. }
  10663. };
  10664. Database.prototype.loadImageFromDB = function (url, image) {
  10665. var _this = this;
  10666. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10667. var saveAndLoadImage = function () {
  10668. if (!_this.hasReachedQuota && _this.db !== null) {
  10669. _this._saveImageIntoDBAsync(completeURL, image);
  10670. } else {
  10671. image.src = url;
  10672. }
  10673. };
  10674. if (!this.mustUpdateRessources) {
  10675. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10676. } else {
  10677. saveAndLoadImage();
  10678. }
  10679. };
  10680. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10681. if (this.isSupported && this.db !== null) {
  10682. var texture;
  10683. var transaction = this.db.transaction(["textures"]);
  10684. transaction.onabort = function (event) {
  10685. image.src = url;
  10686. };
  10687. transaction.oncomplete = function (event) {
  10688. var blobTextureURL;
  10689. if (texture) {
  10690. var URL = window.URL || window.webkitURL;
  10691. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10692. image.onerror = function () {
  10693. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10694. image.src = url;
  10695. };
  10696. image.src = blobTextureURL;
  10697. } else {
  10698. notInDBCallback();
  10699. }
  10700. };
  10701. var getRequest = transaction.objectStore("textures").get(url);
  10702. getRequest.onsuccess = function (event) {
  10703. texture = (event.target).result;
  10704. };
  10705. getRequest.onerror = function (event) {
  10706. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10707. image.src = url;
  10708. };
  10709. } else {
  10710. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10711. image.src = url;
  10712. }
  10713. };
  10714. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10715. var _this = this;
  10716. if (this.isSupported) {
  10717. var generateBlobUrl = function () {
  10718. var blobTextureURL;
  10719. if (blob) {
  10720. var URL = window.URL || window.webkitURL;
  10721. try {
  10722. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10723. } catch (ex) {
  10724. blobTextureURL = URL.createObjectURL(blob);
  10725. }
  10726. }
  10727. image.src = blobTextureURL;
  10728. };
  10729. if (BABYLON.Database.isUASupportingBlobStorage) {
  10730. var xhr = new XMLHttpRequest(), blob;
  10731. xhr.open("GET", url, true);
  10732. xhr.responseType = "blob";
  10733. xhr.addEventListener("load", function () {
  10734. if (xhr.status === 200) {
  10735. blob = xhr.response;
  10736. var transaction = _this.db.transaction(["textures"], "readwrite");
  10737. transaction.onabort = function (event) {
  10738. try {
  10739. if (event.srcElement.error.name === "QuotaExceededError") {
  10740. this.hasReachedQuota = true;
  10741. }
  10742. } catch (ex) {
  10743. }
  10744. generateBlobUrl();
  10745. };
  10746. transaction.oncomplete = function (event) {
  10747. generateBlobUrl();
  10748. };
  10749. var newTexture = { textureUrl: url, data: blob };
  10750. try {
  10751. var addRequest = transaction.objectStore("textures").put(newTexture);
  10752. addRequest.onsuccess = function (event) {
  10753. };
  10754. addRequest.onerror = function (event) {
  10755. generateBlobUrl();
  10756. };
  10757. } catch (ex) {
  10758. if (ex.code === 25) {
  10759. BABYLON.Database.isUASupportingBlobStorage = false;
  10760. }
  10761. image.src = url;
  10762. }
  10763. } else {
  10764. image.src = url;
  10765. }
  10766. }, false);
  10767. xhr.addEventListener("error", function (event) {
  10768. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10769. image.src = url;
  10770. }, false);
  10771. xhr.send();
  10772. } else {
  10773. image.src = url;
  10774. }
  10775. } else {
  10776. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10777. image.src = url;
  10778. }
  10779. };
  10780. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10781. var _this = this;
  10782. var updateVersion = function (event) {
  10783. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10784. };
  10785. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10786. };
  10787. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10788. var _this = this;
  10789. if (this.isSupported) {
  10790. var version;
  10791. try {
  10792. var transaction = this.db.transaction(["versions"]);
  10793. transaction.oncomplete = function (event) {
  10794. if (version) {
  10795. if (_this.manifestVersionFound > version.data) {
  10796. _this.mustUpdateRessources = true;
  10797. updateInDBCallback();
  10798. } else {
  10799. callback(version.data);
  10800. }
  10801. } else {
  10802. _this.mustUpdateRessources = true;
  10803. updateInDBCallback();
  10804. }
  10805. };
  10806. transaction.onabort = function (event) {
  10807. callback(-1);
  10808. };
  10809. var getRequest = transaction.objectStore("versions").get(url);
  10810. getRequest.onsuccess = function (event) {
  10811. version = (event.target).result;
  10812. };
  10813. getRequest.onerror = function (event) {
  10814. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10815. callback(-1);
  10816. };
  10817. } catch (ex) {
  10818. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10819. callback(-1);
  10820. }
  10821. } else {
  10822. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10823. callback(-1);
  10824. }
  10825. };
  10826. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10827. var _this = this;
  10828. if (this.isSupported && !this.hasReachedQuota) {
  10829. try {
  10830. var transaction = this.db.transaction(["versions"], "readwrite");
  10831. transaction.onabort = function (event) {
  10832. try {
  10833. if (event.srcElement.error.name === "QuotaExceededError") {
  10834. _this.hasReachedQuota = true;
  10835. }
  10836. } catch (ex) {
  10837. }
  10838. callback(-1);
  10839. };
  10840. transaction.oncomplete = function (event) {
  10841. callback(_this.manifestVersionFound);
  10842. };
  10843. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10844. var addRequest = transaction.objectStore("versions").put(newVersion);
  10845. addRequest.onsuccess = function (event) {
  10846. };
  10847. addRequest.onerror = function (event) {
  10848. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10849. };
  10850. } catch (ex) {
  10851. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10852. callback(-1);
  10853. }
  10854. } else {
  10855. callback(-1);
  10856. }
  10857. };
  10858. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10859. var _this = this;
  10860. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10861. var saveAndLoadFile = function (event) {
  10862. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10863. };
  10864. this._checkVersionFromDB(completeUrl, function (version) {
  10865. if (version !== -1) {
  10866. if (!_this.mustUpdateRessources) {
  10867. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10868. } else {
  10869. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10870. }
  10871. } else {
  10872. errorCallback();
  10873. }
  10874. });
  10875. };
  10876. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10877. if (this.isSupported) {
  10878. var targetStore;
  10879. if (url.indexOf(".babylon") !== -1) {
  10880. targetStore = "scenes";
  10881. } else {
  10882. targetStore = "textures";
  10883. }
  10884. var file;
  10885. var transaction = this.db.transaction([targetStore]);
  10886. transaction.oncomplete = function (event) {
  10887. if (file) {
  10888. callback(file.data);
  10889. } else {
  10890. notInDBCallback();
  10891. }
  10892. };
  10893. transaction.onabort = function (event) {
  10894. notInDBCallback();
  10895. };
  10896. var getRequest = transaction.objectStore(targetStore).get(url);
  10897. getRequest.onsuccess = function (event) {
  10898. file = (event.target).result;
  10899. };
  10900. getRequest.onerror = function (event) {
  10901. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10902. notInDBCallback();
  10903. };
  10904. } else {
  10905. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10906. callback();
  10907. }
  10908. };
  10909. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10910. var _this = this;
  10911. if (this.isSupported) {
  10912. var targetStore;
  10913. if (url.indexOf(".babylon") !== -1) {
  10914. targetStore = "scenes";
  10915. } else {
  10916. targetStore = "textures";
  10917. }
  10918. var xhr = new XMLHttpRequest(), fileData;
  10919. xhr.open("GET", url, true);
  10920. if (useArrayBuffer) {
  10921. xhr.responseType = "arraybuffer";
  10922. }
  10923. xhr.onprogress = progressCallback;
  10924. xhr.addEventListener("load", function () {
  10925. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10926. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10927. if (!_this.hasReachedQuota) {
  10928. var transaction = _this.db.transaction([targetStore], "readwrite");
  10929. transaction.onabort = function (event) {
  10930. try {
  10931. if (event.srcElement.error.name === "QuotaExceededError") {
  10932. this.hasReachedQuota = true;
  10933. }
  10934. } catch (ex) {
  10935. }
  10936. callback(fileData);
  10937. };
  10938. transaction.oncomplete = function (event) {
  10939. callback(fileData);
  10940. };
  10941. var newFile;
  10942. if (targetStore === "scenes") {
  10943. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10944. } else {
  10945. newFile = { textureUrl: url, data: fileData };
  10946. }
  10947. try {
  10948. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10949. addRequest.onsuccess = function (event) {
  10950. };
  10951. addRequest.onerror = function (event) {
  10952. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10953. };
  10954. } catch (ex) {
  10955. callback(fileData);
  10956. }
  10957. } else {
  10958. callback(fileData);
  10959. }
  10960. } else {
  10961. callback();
  10962. }
  10963. }, false);
  10964. xhr.addEventListener("error", function (event) {
  10965. BABYLON.Tools.Error("error on XHR request.");
  10966. callback();
  10967. }, false);
  10968. xhr.send();
  10969. } else {
  10970. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10971. callback();
  10972. }
  10973. };
  10974. Database.isUASupportingBlobStorage = true;
  10975. Database.parseURL = function (url) {
  10976. var a = document.createElement('a');
  10977. a.href = url;
  10978. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10979. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10980. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10981. return absLocation;
  10982. };
  10983. Database.ReturnFullUrlLocation = function (url) {
  10984. if (url.indexOf("http:/") === -1) {
  10985. return (BABYLON.Database.parseURL(window.location.href) + url);
  10986. } else {
  10987. return url;
  10988. }
  10989. };
  10990. return Database;
  10991. })();
  10992. BABYLON.Database = Database;
  10993. })(BABYLON || (BABYLON = {}));
  10994. var BABYLON;
  10995. (function (BABYLON) {
  10996. var SpriteManager = (function () {
  10997. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10998. this.name = name;
  10999. this.cellSize = cellSize;
  11000. this.sprites = new Array();
  11001. this.renderingGroupId = 0;
  11002. this._vertexDeclaration = [3, 4, 4, 4];
  11003. this._vertexStrideSize = 15 * 4;
  11004. this._capacity = capacity;
  11005. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11006. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11007. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11008. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11009. this._scene = scene;
  11010. this._scene.spriteManagers.push(this);
  11011. this._vertexDeclaration = [3, 4, 4, 4];
  11012. this._vertexStrideSize = 15 * 4;
  11013. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11014. var indices = [];
  11015. var index = 0;
  11016. for (var count = 0; count < capacity; count++) {
  11017. indices.push(index);
  11018. indices.push(index + 1);
  11019. indices.push(index + 2);
  11020. indices.push(index);
  11021. indices.push(index + 2);
  11022. indices.push(index + 3);
  11023. index += 4;
  11024. }
  11025. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11026. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11027. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11028. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11029. }
  11030. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11031. var arrayOffset = index * 15;
  11032. if (offsetX == 0)
  11033. offsetX = this._epsilon;
  11034. else if (offsetX == 1)
  11035. offsetX = 1 - this._epsilon;
  11036. if (offsetY == 0)
  11037. offsetY = this._epsilon;
  11038. else if (offsetY == 1)
  11039. offsetY = 1 - this._epsilon;
  11040. this._vertices[arrayOffset] = sprite.position.x;
  11041. this._vertices[arrayOffset + 1] = sprite.position.y;
  11042. this._vertices[arrayOffset + 2] = sprite.position.z;
  11043. this._vertices[arrayOffset + 3] = sprite.angle;
  11044. this._vertices[arrayOffset + 4] = sprite.size;
  11045. this._vertices[arrayOffset + 5] = offsetX;
  11046. this._vertices[arrayOffset + 6] = offsetY;
  11047. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11048. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11049. var offset = (sprite.cellIndex / rowSize) >> 0;
  11050. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11051. this._vertices[arrayOffset + 10] = offset;
  11052. this._vertices[arrayOffset + 11] = sprite.color.r;
  11053. this._vertices[arrayOffset + 12] = sprite.color.g;
  11054. this._vertices[arrayOffset + 13] = sprite.color.b;
  11055. this._vertices[arrayOffset + 14] = sprite.color.a;
  11056. };
  11057. SpriteManager.prototype.render = function () {
  11058. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11059. return;
  11060. var engine = this._scene.getEngine();
  11061. var baseSize = this._spriteTexture.getBaseSize();
  11062. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11063. var max = Math.min(this._capacity, this.sprites.length);
  11064. var rowSize = baseSize.width / this.cellSize;
  11065. var offset = 0;
  11066. for (var index = 0; index < max; index++) {
  11067. var sprite = this.sprites[index];
  11068. if (!sprite) {
  11069. continue;
  11070. }
  11071. sprite._animate(deltaTime);
  11072. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11073. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11074. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11075. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11076. }
  11077. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11078. var effect = this._effectBase;
  11079. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11080. effect = this._effectFog;
  11081. }
  11082. engine.enableEffect(effect);
  11083. var viewMatrix = this._scene.getViewMatrix();
  11084. effect.setTexture("diffuseSampler", this._spriteTexture);
  11085. effect.setMatrix("view", viewMatrix);
  11086. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11087. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11088. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11089. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11090. effect.setColor3("vFogColor", this._scene.fogColor);
  11091. }
  11092. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11093. effect.setBool("alphaTest", true);
  11094. engine.setColorWrite(false);
  11095. engine.draw(true, 0, max * 6);
  11096. engine.setColorWrite(true);
  11097. effect.setBool("alphaTest", false);
  11098. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11099. engine.draw(true, 0, max * 6);
  11100. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11101. };
  11102. SpriteManager.prototype.dispose = function () {
  11103. if (this._vertexBuffer) {
  11104. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11105. this._vertexBuffer = null;
  11106. }
  11107. if (this._indexBuffer) {
  11108. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11109. this._indexBuffer = null;
  11110. }
  11111. if (this._spriteTexture) {
  11112. this._spriteTexture.dispose();
  11113. this._spriteTexture = null;
  11114. }
  11115. var index = this._scene.spriteManagers.indexOf(this);
  11116. this._scene.spriteManagers.splice(index, 1);
  11117. if (this.onDispose) {
  11118. this.onDispose();
  11119. }
  11120. };
  11121. return SpriteManager;
  11122. })();
  11123. BABYLON.SpriteManager = SpriteManager;
  11124. })(BABYLON || (BABYLON = {}));
  11125. var BABYLON;
  11126. (function (BABYLON) {
  11127. var Sprite = (function () {
  11128. function Sprite(name, manager) {
  11129. this.name = name;
  11130. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11131. this.size = 1.0;
  11132. this.angle = 0;
  11133. this.cellIndex = 0;
  11134. this.invertU = 0;
  11135. this.invertV = 0;
  11136. this.animations = new Array();
  11137. this._animationStarted = false;
  11138. this._loopAnimation = false;
  11139. this._fromIndex = 0;
  11140. this._toIndex = 0;
  11141. this._delay = 0;
  11142. this._direction = 1;
  11143. this._frameCount = 0;
  11144. this._time = 0;
  11145. this._manager = manager;
  11146. this._manager.sprites.push(this);
  11147. this.position = BABYLON.Vector3.Zero();
  11148. }
  11149. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11150. this._fromIndex = from;
  11151. this._toIndex = to;
  11152. this._loopAnimation = loop;
  11153. this._delay = delay;
  11154. this._animationStarted = true;
  11155. this._direction = from < to ? 1 : -1;
  11156. this.cellIndex = from;
  11157. this._time = 0;
  11158. };
  11159. Sprite.prototype.stopAnimation = function () {
  11160. this._animationStarted = false;
  11161. };
  11162. Sprite.prototype._animate = function (deltaTime) {
  11163. if (!this._animationStarted)
  11164. return;
  11165. this._time += deltaTime;
  11166. if (this._time > this._delay) {
  11167. this._time = this._time % this._delay;
  11168. this.cellIndex += this._direction;
  11169. if (this.cellIndex == this._toIndex) {
  11170. if (this._loopAnimation) {
  11171. this.cellIndex = this._fromIndex;
  11172. } else {
  11173. this._animationStarted = false;
  11174. if (this.disposeWhenFinishedAnimating) {
  11175. this.dispose();
  11176. }
  11177. }
  11178. }
  11179. }
  11180. };
  11181. Sprite.prototype.dispose = function () {
  11182. for (var i = 0; i < this._manager.sprites.length; i++) {
  11183. if (this._manager.sprites[i] == this) {
  11184. this._manager.sprites.splice(i, 1);
  11185. }
  11186. }
  11187. };
  11188. return Sprite;
  11189. })();
  11190. BABYLON.Sprite = Sprite;
  11191. })(BABYLON || (BABYLON = {}));
  11192. var BABYLON;
  11193. (function (BABYLON) {
  11194. var Layer = (function () {
  11195. function Layer(name, imgUrl, scene, isBackground, color) {
  11196. this.name = name;
  11197. this._vertexDeclaration = [2];
  11198. this._vertexStrideSize = 2 * 4;
  11199. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11200. this.isBackground = isBackground === undefined ? true : isBackground;
  11201. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11202. this._scene = scene;
  11203. this._scene.layers.push(this);
  11204. var vertices = [];
  11205. vertices.push(1, 1);
  11206. vertices.push(-1, 1);
  11207. vertices.push(-1, -1);
  11208. vertices.push(1, -1);
  11209. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11210. var indices = [];
  11211. indices.push(0);
  11212. indices.push(1);
  11213. indices.push(2);
  11214. indices.push(0);
  11215. indices.push(2);
  11216. indices.push(3);
  11217. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11218. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11219. }
  11220. Layer.prototype.render = function () {
  11221. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11222. return;
  11223. var engine = this._scene.getEngine();
  11224. engine.enableEffect(this._effect);
  11225. engine.setState(false);
  11226. this._effect.setTexture("textureSampler", this.texture);
  11227. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11228. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11229. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11230. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11231. engine.draw(true, 0, 6);
  11232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11233. };
  11234. Layer.prototype.dispose = function () {
  11235. if (this._vertexBuffer) {
  11236. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11237. this._vertexBuffer = null;
  11238. }
  11239. if (this._indexBuffer) {
  11240. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11241. this._indexBuffer = null;
  11242. }
  11243. if (this.texture) {
  11244. this.texture.dispose();
  11245. this.texture = null;
  11246. }
  11247. var index = this._scene.layers.indexOf(this);
  11248. this._scene.layers.splice(index, 1);
  11249. if (this.onDispose) {
  11250. this.onDispose();
  11251. }
  11252. };
  11253. return Layer;
  11254. })();
  11255. BABYLON.Layer = Layer;
  11256. })(BABYLON || (BABYLON = {}));
  11257. var BABYLON;
  11258. (function (BABYLON) {
  11259. var Particle = (function () {
  11260. function Particle() {
  11261. this.position = BABYLON.Vector3.Zero();
  11262. this.direction = BABYLON.Vector3.Zero();
  11263. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11264. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11265. this.lifeTime = 1.0;
  11266. this.age = 0;
  11267. this.size = 0;
  11268. this.angle = 0;
  11269. this.angularSpeed = 0;
  11270. }
  11271. return Particle;
  11272. })();
  11273. BABYLON.Particle = Particle;
  11274. })(BABYLON || (BABYLON = {}));
  11275. var BABYLON;
  11276. (function (BABYLON) {
  11277. var randomNumber = function (min, max) {
  11278. if (min == max) {
  11279. return (min);
  11280. }
  11281. var random = Math.random();
  11282. return ((random * (max - min)) + min);
  11283. };
  11284. var ParticleSystem = (function () {
  11285. function ParticleSystem(name, capacity, scene, customEffect) {
  11286. var _this = this;
  11287. this.name = name;
  11288. this.renderingGroupId = 0;
  11289. this.emitter = null;
  11290. this.emitRate = 10;
  11291. this.manualEmitCount = -1;
  11292. this.updateSpeed = 0.01;
  11293. this.targetStopDuration = 0;
  11294. this.disposeOnStop = false;
  11295. this.minEmitPower = 1;
  11296. this.maxEmitPower = 1;
  11297. this.minLifeTime = 1;
  11298. this.maxLifeTime = 1;
  11299. this.minSize = 1;
  11300. this.maxSize = 1;
  11301. this.minAngularSpeed = 0;
  11302. this.maxAngularSpeed = 0;
  11303. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11304. this.forceDepthWrite = false;
  11305. this.gravity = BABYLON.Vector3.Zero();
  11306. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11307. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11308. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11309. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11310. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11311. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11312. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11313. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11314. this.particles = new Array();
  11315. this._vertexDeclaration = [3, 4, 4];
  11316. this._vertexStrideSize = 11 * 4;
  11317. this._stockParticles = new Array();
  11318. this._newPartsExcess = 0;
  11319. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11320. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11321. this._scaledDirection = BABYLON.Vector3.Zero();
  11322. this._scaledGravity = BABYLON.Vector3.Zero();
  11323. this._currentRenderId = -1;
  11324. this._started = false;
  11325. this._stopped = false;
  11326. this._actualFrame = 0;
  11327. this.id = name;
  11328. this._capacity = capacity;
  11329. this._scene = scene;
  11330. this._customEffect = customEffect;
  11331. scene.particleSystems.push(this);
  11332. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11333. var indices = [];
  11334. var index = 0;
  11335. for (var count = 0; count < capacity; count++) {
  11336. indices.push(index);
  11337. indices.push(index + 1);
  11338. indices.push(index + 2);
  11339. indices.push(index);
  11340. indices.push(index + 2);
  11341. indices.push(index + 3);
  11342. index += 4;
  11343. }
  11344. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11345. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11346. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11347. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11348. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11349. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11350. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11351. };
  11352. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11353. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11354. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11355. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11356. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11357. };
  11358. }
  11359. ParticleSystem.prototype.getCapacity = function () {
  11360. return this._capacity;
  11361. };
  11362. ParticleSystem.prototype.isAlive = function () {
  11363. return this._alive;
  11364. };
  11365. ParticleSystem.prototype.isStarted = function () {
  11366. return this._started;
  11367. };
  11368. ParticleSystem.prototype.start = function () {
  11369. this._started = true;
  11370. this._stopped = false;
  11371. this._actualFrame = 0;
  11372. };
  11373. ParticleSystem.prototype.stop = function () {
  11374. this._stopped = true;
  11375. };
  11376. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11377. var offset = index * 11;
  11378. this._vertices[offset] = particle.position.x;
  11379. this._vertices[offset + 1] = particle.position.y;
  11380. this._vertices[offset + 2] = particle.position.z;
  11381. this._vertices[offset + 3] = particle.color.r;
  11382. this._vertices[offset + 4] = particle.color.g;
  11383. this._vertices[offset + 5] = particle.color.b;
  11384. this._vertices[offset + 6] = particle.color.a;
  11385. this._vertices[offset + 7] = particle.angle;
  11386. this._vertices[offset + 8] = particle.size;
  11387. this._vertices[offset + 9] = offsetX;
  11388. this._vertices[offset + 10] = offsetY;
  11389. };
  11390. ParticleSystem.prototype._update = function (newParticles) {
  11391. this._alive = this.particles.length > 0;
  11392. for (var index = 0; index < this.particles.length; index++) {
  11393. var particle = this.particles[index];
  11394. particle.age += this._scaledUpdateSpeed;
  11395. if (particle.age >= particle.lifeTime) {
  11396. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11397. index--;
  11398. continue;
  11399. } else {
  11400. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11401. particle.color.addInPlace(this._scaledColorStep);
  11402. if (particle.color.a < 0)
  11403. particle.color.a = 0;
  11404. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11405. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11406. particle.position.addInPlace(this._scaledDirection);
  11407. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11408. particle.direction.addInPlace(this._scaledGravity);
  11409. }
  11410. }
  11411. var worldMatrix;
  11412. if (this.emitter.position) {
  11413. worldMatrix = this.emitter.getWorldMatrix();
  11414. } else {
  11415. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11416. }
  11417. for (index = 0; index < newParticles; index++) {
  11418. if (this.particles.length == this._capacity) {
  11419. break;
  11420. }
  11421. if (this._stockParticles.length !== 0) {
  11422. particle = this._stockParticles.pop();
  11423. particle.age = 0;
  11424. } else {
  11425. particle = new BABYLON.Particle();
  11426. }
  11427. this.particles.push(particle);
  11428. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11429. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11430. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11431. particle.size = randomNumber(this.minSize, this.maxSize);
  11432. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11433. this.startPositionFunction(worldMatrix, particle.position);
  11434. var step = randomNumber(0, 1.0);
  11435. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11436. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11437. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11438. }
  11439. };
  11440. ParticleSystem.prototype._getEffect = function () {
  11441. if (this._customEffect) {
  11442. return this._customEffect;
  11443. }
  11444. ;
  11445. var defines = [];
  11446. if (this._scene.clipPlane) {
  11447. defines.push("#define CLIPPLANE");
  11448. }
  11449. var join = defines.join("\n");
  11450. if (this._cachedDefines != join) {
  11451. this._cachedDefines = join;
  11452. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11453. }
  11454. return this._effect;
  11455. };
  11456. ParticleSystem.prototype.animate = function () {
  11457. if (!this._started)
  11458. return;
  11459. var effect = this._getEffect();
  11460. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11461. return;
  11462. if (this._currentRenderId === this._scene.getRenderId()) {
  11463. return;
  11464. }
  11465. this._currentRenderId = this._scene.getRenderId();
  11466. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11467. var emitCout;
  11468. if (this.manualEmitCount > -1) {
  11469. emitCout = this.manualEmitCount;
  11470. this.manualEmitCount = 0;
  11471. } else {
  11472. emitCout = this.emitRate;
  11473. }
  11474. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11475. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11476. if (this._newPartsExcess > 1.0) {
  11477. newParticles += this._newPartsExcess >> 0;
  11478. this._newPartsExcess -= this._newPartsExcess >> 0;
  11479. }
  11480. this._alive = false;
  11481. if (!this._stopped) {
  11482. this._actualFrame += this._scaledUpdateSpeed;
  11483. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11484. this.stop();
  11485. } else {
  11486. newParticles = 0;
  11487. }
  11488. this._update(newParticles);
  11489. if (this._stopped) {
  11490. if (!this._alive) {
  11491. this._started = false;
  11492. if (this.disposeOnStop) {
  11493. this._scene._toBeDisposed.push(this);
  11494. }
  11495. }
  11496. }
  11497. var offset = 0;
  11498. for (var index = 0; index < this.particles.length; index++) {
  11499. var particle = this.particles[index];
  11500. this._appendParticleVertex(offset++, particle, 0, 0);
  11501. this._appendParticleVertex(offset++, particle, 1, 0);
  11502. this._appendParticleVertex(offset++, particle, 1, 1);
  11503. this._appendParticleVertex(offset++, particle, 0, 1);
  11504. }
  11505. var engine = this._scene.getEngine();
  11506. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11507. };
  11508. ParticleSystem.prototype.render = function () {
  11509. var effect = this._getEffect();
  11510. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11511. return 0;
  11512. var engine = this._scene.getEngine();
  11513. engine.enableEffect(effect);
  11514. var viewMatrix = this._scene.getViewMatrix();
  11515. effect.setTexture("diffuseSampler", this.particleTexture);
  11516. effect.setMatrix("view", viewMatrix);
  11517. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11518. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11519. if (this._scene.clipPlane) {
  11520. var clipPlane = this._scene.clipPlane;
  11521. var invView = viewMatrix.clone();
  11522. invView.invert();
  11523. effect.setMatrix("invView", invView);
  11524. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11525. }
  11526. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11527. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11528. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11529. } else {
  11530. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11531. }
  11532. if (this.forceDepthWrite) {
  11533. engine.setDepthWrite(true);
  11534. }
  11535. engine.draw(true, 0, this.particles.length * 6);
  11536. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11537. return this.particles.length;
  11538. };
  11539. ParticleSystem.prototype.dispose = function () {
  11540. if (this._vertexBuffer) {
  11541. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11542. this._vertexBuffer = null;
  11543. }
  11544. if (this._indexBuffer) {
  11545. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11546. this._indexBuffer = null;
  11547. }
  11548. if (this.particleTexture) {
  11549. this.particleTexture.dispose();
  11550. this.particleTexture = null;
  11551. }
  11552. var index = this._scene.particleSystems.indexOf(this);
  11553. this._scene.particleSystems.splice(index, 1);
  11554. if (this.onDispose) {
  11555. this.onDispose();
  11556. }
  11557. };
  11558. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11559. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11560. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11561. if (newEmitter === undefined) {
  11562. newEmitter = this.emitter;
  11563. }
  11564. result.emitter = newEmitter;
  11565. if (this.particleTexture) {
  11566. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11567. }
  11568. result.start();
  11569. return result;
  11570. };
  11571. ParticleSystem.BLENDMODE_ONEONE = 0;
  11572. ParticleSystem.BLENDMODE_STANDARD = 1;
  11573. return ParticleSystem;
  11574. })();
  11575. BABYLON.ParticleSystem = ParticleSystem;
  11576. })(BABYLON || (BABYLON = {}));
  11577. var BABYLON;
  11578. (function (BABYLON) {
  11579. var Animation = (function () {
  11580. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11581. this.name = name;
  11582. this.targetProperty = targetProperty;
  11583. this.framePerSecond = framePerSecond;
  11584. this.dataType = dataType;
  11585. this.loopMode = loopMode;
  11586. this._offsetsCache = {};
  11587. this._highLimitsCache = {};
  11588. this._stopped = false;
  11589. this.targetPropertyPath = targetProperty.split(".");
  11590. this.dataType = dataType;
  11591. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11592. }
  11593. Animation.prototype.isStopped = function () {
  11594. return this._stopped;
  11595. };
  11596. Animation.prototype.getKeys = function () {
  11597. return this._keys;
  11598. };
  11599. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11600. return startValue + (endValue - startValue) * gradient;
  11601. };
  11602. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11603. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11604. };
  11605. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11606. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11607. };
  11608. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11609. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11610. };
  11611. Animation.prototype.clone = function () {
  11612. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11613. clone.setKeys(this._keys);
  11614. return clone;
  11615. };
  11616. Animation.prototype.setKeys = function (values) {
  11617. this._keys = values.slice(0);
  11618. this._offsetsCache = {};
  11619. this._highLimitsCache = {};
  11620. };
  11621. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11622. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11623. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11624. }
  11625. this.currentFrame = currentFrame;
  11626. for (var key = 0; key < this._keys.length; key++) {
  11627. if (this._keys[key + 1].frame >= currentFrame) {
  11628. var startValue = this._keys[key].value;
  11629. var endValue = this._keys[key + 1].value;
  11630. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11631. switch (this.dataType) {
  11632. case Animation.ANIMATIONTYPE_FLOAT:
  11633. switch (loopMode) {
  11634. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11635. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11636. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11637. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11638. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11639. }
  11640. break;
  11641. case Animation.ANIMATIONTYPE_QUATERNION:
  11642. var quaternion = null;
  11643. switch (loopMode) {
  11644. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11645. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11646. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11647. break;
  11648. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11649. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11650. break;
  11651. }
  11652. return quaternion;
  11653. case Animation.ANIMATIONTYPE_VECTOR3:
  11654. switch (loopMode) {
  11655. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11656. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11657. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11658. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11659. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11660. }
  11661. case Animation.ANIMATIONTYPE_COLOR3:
  11662. switch (loopMode) {
  11663. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11664. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11665. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11666. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11667. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11668. }
  11669. case Animation.ANIMATIONTYPE_MATRIX:
  11670. switch (loopMode) {
  11671. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11672. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11673. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11674. return startValue;
  11675. }
  11676. default:
  11677. break;
  11678. }
  11679. break;
  11680. }
  11681. }
  11682. return this._keys[this._keys.length - 1].value;
  11683. };
  11684. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11685. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11686. this._stopped = true;
  11687. return false;
  11688. }
  11689. var returnValue = true;
  11690. if (this._keys[0].frame != 0) {
  11691. var newKey = {
  11692. frame: 0,
  11693. value: this._keys[0].value
  11694. };
  11695. this._keys.splice(0, 0, newKey);
  11696. }
  11697. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11698. from = this._keys[0].frame;
  11699. }
  11700. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11701. to = this._keys[this._keys.length - 1].frame;
  11702. }
  11703. var range = to - from;
  11704. var offsetValue;
  11705. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11706. if (ratio > range && !loop) {
  11707. returnValue = false;
  11708. highLimitValue = this._keys[this._keys.length - 1].value;
  11709. } else {
  11710. var highLimitValue = 0;
  11711. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11712. var keyOffset = to.toString() + from.toString();
  11713. if (!this._offsetsCache[keyOffset]) {
  11714. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11715. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11716. switch (this.dataType) {
  11717. case Animation.ANIMATIONTYPE_FLOAT:
  11718. this._offsetsCache[keyOffset] = toValue - fromValue;
  11719. break;
  11720. case Animation.ANIMATIONTYPE_QUATERNION:
  11721. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11722. break;
  11723. case Animation.ANIMATIONTYPE_VECTOR3:
  11724. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11725. case Animation.ANIMATIONTYPE_COLOR3:
  11726. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11727. default:
  11728. break;
  11729. }
  11730. this._highLimitsCache[keyOffset] = toValue;
  11731. }
  11732. highLimitValue = this._highLimitsCache[keyOffset];
  11733. offsetValue = this._offsetsCache[keyOffset];
  11734. }
  11735. }
  11736. if (offsetValue === undefined) {
  11737. switch (this.dataType) {
  11738. case Animation.ANIMATIONTYPE_FLOAT:
  11739. offsetValue = 0;
  11740. break;
  11741. case Animation.ANIMATIONTYPE_QUATERNION:
  11742. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11743. break;
  11744. case Animation.ANIMATIONTYPE_VECTOR3:
  11745. offsetValue = BABYLON.Vector3.Zero();
  11746. break;
  11747. case Animation.ANIMATIONTYPE_COLOR3:
  11748. offsetValue = BABYLON.Color3.Black();
  11749. }
  11750. }
  11751. var repeatCount = (ratio / range) >> 0;
  11752. var currentFrame = returnValue ? from + ratio % range : to;
  11753. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11754. if (this.targetPropertyPath.length > 1) {
  11755. var property = this._target[this.targetPropertyPath[0]];
  11756. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11757. property = property[this.targetPropertyPath[index]];
  11758. }
  11759. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11760. } else {
  11761. this._target[this.targetPropertyPath[0]] = currentValue;
  11762. }
  11763. if (this._target.markAsDirty) {
  11764. this._target.markAsDirty(this.targetProperty);
  11765. }
  11766. if (!returnValue) {
  11767. this._stopped = true;
  11768. }
  11769. return returnValue;
  11770. };
  11771. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11772. get: function () {
  11773. return Animation._ANIMATIONTYPE_FLOAT;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11779. get: function () {
  11780. return Animation._ANIMATIONTYPE_VECTOR3;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11786. get: function () {
  11787. return Animation._ANIMATIONTYPE_QUATERNION;
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11793. get: function () {
  11794. return Animation._ANIMATIONTYPE_MATRIX;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11800. get: function () {
  11801. return Animation._ANIMATIONTYPE_COLOR3;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11807. get: function () {
  11808. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11814. get: function () {
  11815. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11821. get: function () {
  11822. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Animation._ANIMATIONTYPE_FLOAT = 0;
  11828. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11829. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11830. Animation._ANIMATIONTYPE_MATRIX = 3;
  11831. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11832. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11833. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11834. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11835. return Animation;
  11836. })();
  11837. BABYLON.Animation = Animation;
  11838. })(BABYLON || (BABYLON = {}));
  11839. var BABYLON;
  11840. (function (BABYLON) {
  11841. var Animatable = (function () {
  11842. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11843. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11844. if (typeof toFrame === "undefined") { toFrame = 100; }
  11845. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11846. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11847. this.target = target;
  11848. this.fromFrame = fromFrame;
  11849. this.toFrame = toFrame;
  11850. this.loopAnimation = loopAnimation;
  11851. this.speedRatio = speedRatio;
  11852. this.onAnimationEnd = onAnimationEnd;
  11853. this._animations = new Array();
  11854. this._paused = false;
  11855. this.animationStarted = false;
  11856. if (animations) {
  11857. this.appendAnimations(target, animations);
  11858. }
  11859. this._scene = scene;
  11860. scene._activeAnimatables.push(this);
  11861. }
  11862. Animatable.prototype.appendAnimations = function (target, animations) {
  11863. for (var index = 0; index < animations.length; index++) {
  11864. var animation = animations[index];
  11865. animation._target = target;
  11866. this._animations.push(animation);
  11867. }
  11868. };
  11869. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11870. var animations = this._animations;
  11871. for (var index = 0; index < animations.length; index++) {
  11872. if (animations[index].targetProperty === property) {
  11873. return animations[index];
  11874. }
  11875. }
  11876. return null;
  11877. };
  11878. Animatable.prototype.pause = function () {
  11879. this._paused = true;
  11880. };
  11881. Animatable.prototype.restart = function () {
  11882. this._paused = false;
  11883. };
  11884. Animatable.prototype.stop = function () {
  11885. var index = this._scene._activeAnimatables.indexOf(this);
  11886. if (index > -1) {
  11887. this._scene._activeAnimatables.splice(index, 1);
  11888. }
  11889. if (this.onAnimationEnd) {
  11890. this.onAnimationEnd();
  11891. }
  11892. };
  11893. Animatable.prototype._animate = function (delay) {
  11894. if (this._paused) {
  11895. return true;
  11896. }
  11897. if (!this._localDelayOffset) {
  11898. this._localDelayOffset = delay;
  11899. }
  11900. var running = false;
  11901. var animations = this._animations;
  11902. for (var index = 0; index < animations.length; index++) {
  11903. var animation = animations[index];
  11904. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11905. running = running || isRunning;
  11906. }
  11907. if (!running && this.onAnimationEnd) {
  11908. this.onAnimationEnd();
  11909. }
  11910. return running;
  11911. };
  11912. return Animatable;
  11913. })();
  11914. BABYLON.Animatable = Animatable;
  11915. })(BABYLON || (BABYLON = {}));
  11916. var BABYLON;
  11917. (function (BABYLON) {
  11918. var Octree = (function () {
  11919. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11920. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11921. this.maxDepth = maxDepth;
  11922. this.dynamicContent = new Array();
  11923. this._maxBlockCapacity = maxBlockCapacity || 64;
  11924. this._selectionContent = new BABYLON.SmartArray(1024);
  11925. this._creationFunc = creationFunc;
  11926. }
  11927. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11928. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11929. };
  11930. Octree.prototype.addMesh = function (entry) {
  11931. for (var index = 0; index < this.blocks.length; index++) {
  11932. var block = this.blocks[index];
  11933. block.addEntry(entry);
  11934. }
  11935. };
  11936. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11937. this._selectionContent.reset();
  11938. for (var index = 0; index < this.blocks.length; index++) {
  11939. var block = this.blocks[index];
  11940. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11941. }
  11942. if (allowDuplicate) {
  11943. this._selectionContent.concat(this.dynamicContent);
  11944. } else {
  11945. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11946. }
  11947. return this._selectionContent;
  11948. };
  11949. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11950. this._selectionContent.reset();
  11951. for (var index = 0; index < this.blocks.length; index++) {
  11952. var block = this.blocks[index];
  11953. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11954. }
  11955. if (allowDuplicate) {
  11956. this._selectionContent.concat(this.dynamicContent);
  11957. } else {
  11958. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11959. }
  11960. return this._selectionContent;
  11961. };
  11962. Octree.prototype.intersectsRay = function (ray) {
  11963. this._selectionContent.reset();
  11964. for (var index = 0; index < this.blocks.length; index++) {
  11965. var block = this.blocks[index];
  11966. block.intersectsRay(ray, this._selectionContent);
  11967. }
  11968. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11969. return this._selectionContent;
  11970. };
  11971. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11972. target.blocks = new Array();
  11973. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11974. for (var x = 0; x < 2; x++) {
  11975. for (var y = 0; y < 2; y++) {
  11976. for (var z = 0; z < 2; z++) {
  11977. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11978. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11979. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11980. block.addEntries(entries);
  11981. target.blocks.push(block);
  11982. }
  11983. }
  11984. }
  11985. };
  11986. Octree.CreationFuncForMeshes = function (entry, block) {
  11987. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11988. block.entries.push(entry);
  11989. }
  11990. };
  11991. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11992. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11993. block.entries.push(entry);
  11994. }
  11995. };
  11996. return Octree;
  11997. })();
  11998. BABYLON.Octree = Octree;
  11999. })(BABYLON || (BABYLON = {}));
  12000. var BABYLON;
  12001. (function (BABYLON) {
  12002. var OctreeBlock = (function () {
  12003. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12004. this.entries = new Array();
  12005. this._boundingVectors = new Array();
  12006. this._capacity = capacity;
  12007. this._depth = depth;
  12008. this._maxDepth = maxDepth;
  12009. this._creationFunc = creationFunc;
  12010. this._minPoint = minPoint;
  12011. this._maxPoint = maxPoint;
  12012. this._boundingVectors.push(minPoint.clone());
  12013. this._boundingVectors.push(maxPoint.clone());
  12014. this._boundingVectors.push(minPoint.clone());
  12015. this._boundingVectors[2].x = maxPoint.x;
  12016. this._boundingVectors.push(minPoint.clone());
  12017. this._boundingVectors[3].y = maxPoint.y;
  12018. this._boundingVectors.push(minPoint.clone());
  12019. this._boundingVectors[4].z = maxPoint.z;
  12020. this._boundingVectors.push(maxPoint.clone());
  12021. this._boundingVectors[5].z = minPoint.z;
  12022. this._boundingVectors.push(maxPoint.clone());
  12023. this._boundingVectors[6].x = minPoint.x;
  12024. this._boundingVectors.push(maxPoint.clone());
  12025. this._boundingVectors[7].y = minPoint.y;
  12026. }
  12027. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12028. get: function () {
  12029. return this._capacity;
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12035. get: function () {
  12036. return this._minPoint;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12042. get: function () {
  12043. return this._maxPoint;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. OctreeBlock.prototype.addEntry = function (entry) {
  12049. if (this.blocks) {
  12050. for (var index = 0; index < this.blocks.length; index++) {
  12051. var block = this.blocks[index];
  12052. block.addEntry(entry);
  12053. }
  12054. return;
  12055. }
  12056. this._creationFunc(entry, this);
  12057. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12058. this.createInnerBlocks();
  12059. }
  12060. };
  12061. OctreeBlock.prototype.addEntries = function (entries) {
  12062. for (var index = 0; index < entries.length; index++) {
  12063. var mesh = entries[index];
  12064. this.addEntry(mesh);
  12065. }
  12066. };
  12067. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12068. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12069. if (this.blocks) {
  12070. for (var index = 0; index < this.blocks.length; index++) {
  12071. var block = this.blocks[index];
  12072. block.select(frustumPlanes, selection, allowDuplicate);
  12073. }
  12074. return;
  12075. }
  12076. if (allowDuplicate) {
  12077. selection.concat(this.entries);
  12078. } else {
  12079. selection.concatWithNoDuplicate(this.entries);
  12080. }
  12081. }
  12082. };
  12083. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12084. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12085. if (this.blocks) {
  12086. for (var index = 0; index < this.blocks.length; index++) {
  12087. var block = this.blocks[index];
  12088. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12089. }
  12090. return;
  12091. }
  12092. if (allowDuplicate) {
  12093. selection.concat(this.entries);
  12094. } else {
  12095. selection.concatWithNoDuplicate(this.entries);
  12096. }
  12097. }
  12098. };
  12099. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12100. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12101. if (this.blocks) {
  12102. for (var index = 0; index < this.blocks.length; index++) {
  12103. var block = this.blocks[index];
  12104. block.intersectsRay(ray, selection);
  12105. }
  12106. return;
  12107. }
  12108. selection.concatWithNoDuplicate(this.entries);
  12109. }
  12110. };
  12111. OctreeBlock.prototype.createInnerBlocks = function () {
  12112. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12113. };
  12114. return OctreeBlock;
  12115. })();
  12116. BABYLON.OctreeBlock = OctreeBlock;
  12117. })(BABYLON || (BABYLON = {}));
  12118. var BABYLON;
  12119. (function (BABYLON) {
  12120. var Bone = (function () {
  12121. function Bone(name, skeleton, parentBone, matrix) {
  12122. this.name = name;
  12123. this.children = new Array();
  12124. this.animations = new Array();
  12125. this._worldTransform = new BABYLON.Matrix();
  12126. this._absoluteTransform = new BABYLON.Matrix();
  12127. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12128. this._skeleton = skeleton;
  12129. this._matrix = matrix;
  12130. this._baseMatrix = matrix;
  12131. skeleton.bones.push(this);
  12132. if (parentBone) {
  12133. this._parent = parentBone;
  12134. parentBone.children.push(this);
  12135. } else {
  12136. this._parent = null;
  12137. }
  12138. this._updateDifferenceMatrix();
  12139. }
  12140. Bone.prototype.getParent = function () {
  12141. return this._parent;
  12142. };
  12143. Bone.prototype.getLocalMatrix = function () {
  12144. return this._matrix;
  12145. };
  12146. Bone.prototype.getBaseMatrix = function () {
  12147. return this._baseMatrix;
  12148. };
  12149. Bone.prototype.getWorldMatrix = function () {
  12150. return this._worldTransform;
  12151. };
  12152. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12153. return this._invertedAbsoluteTransform;
  12154. };
  12155. Bone.prototype.getAbsoluteMatrix = function () {
  12156. var matrix = this._matrix.clone();
  12157. var parent = this._parent;
  12158. while (parent) {
  12159. matrix = matrix.multiply(parent.getLocalMatrix());
  12160. parent = parent.getParent();
  12161. }
  12162. return matrix;
  12163. };
  12164. Bone.prototype.updateMatrix = function (matrix) {
  12165. this._matrix = matrix;
  12166. this._skeleton._markAsDirty();
  12167. this._updateDifferenceMatrix();
  12168. };
  12169. Bone.prototype._updateDifferenceMatrix = function () {
  12170. if (this._parent) {
  12171. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12172. } else {
  12173. this._absoluteTransform.copyFrom(this._matrix);
  12174. }
  12175. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12176. for (var index = 0; index < this.children.length; index++) {
  12177. this.children[index]._updateDifferenceMatrix();
  12178. }
  12179. };
  12180. Bone.prototype.markAsDirty = function () {
  12181. this._skeleton._markAsDirty();
  12182. };
  12183. return Bone;
  12184. })();
  12185. BABYLON.Bone = Bone;
  12186. })(BABYLON || (BABYLON = {}));
  12187. var BABYLON;
  12188. (function (BABYLON) {
  12189. var Skeleton = (function () {
  12190. function Skeleton(name, id, scene) {
  12191. this.name = name;
  12192. this.id = id;
  12193. this.bones = new Array();
  12194. this._isDirty = true;
  12195. this._identity = BABYLON.Matrix.Identity();
  12196. this.bones = [];
  12197. this._scene = scene;
  12198. scene.skeletons.push(this);
  12199. }
  12200. Skeleton.prototype.getTransformMatrices = function () {
  12201. return this._transformMatrices;
  12202. };
  12203. Skeleton.prototype._markAsDirty = function () {
  12204. this._isDirty = true;
  12205. };
  12206. Skeleton.prototype.prepare = function () {
  12207. if (!this._isDirty) {
  12208. return;
  12209. }
  12210. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12211. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12212. }
  12213. for (var index = 0; index < this.bones.length; index++) {
  12214. var bone = this.bones[index];
  12215. var parentBone = bone.getParent();
  12216. if (parentBone) {
  12217. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12218. } else {
  12219. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12220. }
  12221. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12222. }
  12223. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12224. this._isDirty = false;
  12225. };
  12226. Skeleton.prototype.getAnimatables = function () {
  12227. if (!this._animatables || this._animatables.length != this.bones.length) {
  12228. this._animatables = [];
  12229. for (var index = 0; index < this.bones.length; index++) {
  12230. this._animatables.push(this.bones[index]);
  12231. }
  12232. }
  12233. return this._animatables;
  12234. };
  12235. Skeleton.prototype.clone = function (name, id) {
  12236. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12237. for (var index = 0; index < this.bones.length; index++) {
  12238. var source = this.bones[index];
  12239. var parentBone = null;
  12240. if (source.getParent()) {
  12241. var parentIndex = this.bones.indexOf(source.getParent());
  12242. parentBone = result.bones[parentIndex];
  12243. }
  12244. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12245. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12246. }
  12247. return result;
  12248. };
  12249. return Skeleton;
  12250. })();
  12251. BABYLON.Skeleton = Skeleton;
  12252. })(BABYLON || (BABYLON = {}));
  12253. var BABYLON;
  12254. (function (BABYLON) {
  12255. var PostProcess = (function () {
  12256. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12257. this.name = name;
  12258. this.width = -1;
  12259. this.height = -1;
  12260. this._reusable = false;
  12261. this._textures = new BABYLON.SmartArray(2);
  12262. this._currentRenderTextureInd = 0;
  12263. if (camera != null) {
  12264. this._camera = camera;
  12265. this._scene = camera.getScene();
  12266. camera.attachPostProcess(this);
  12267. this._engine = this._scene.getEngine();
  12268. } else {
  12269. this._engine = engine;
  12270. }
  12271. this._renderRatio = ratio;
  12272. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12273. this._reusable = reusable || false;
  12274. samplers = samplers || [];
  12275. samplers.push("textureSampler");
  12276. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12277. }
  12278. PostProcess.prototype.isReusable = function () {
  12279. return this._reusable;
  12280. };
  12281. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12282. camera = camera || this._camera;
  12283. var scene = camera.getScene();
  12284. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  12285. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  12286. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  12287. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  12288. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  12289. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12290. if (this._textures.length > 0) {
  12291. for (var i = 0; i < this._textures.length; i++) {
  12292. this._engine._releaseTexture(this._textures.data[i]);
  12293. }
  12294. this._textures.reset();
  12295. }
  12296. this.width = desiredWidth;
  12297. this.height = desiredHeight;
  12298. 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 }));
  12299. if (this._reusable) {
  12300. 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 }));
  12301. }
  12302. if (this.onSizeChanged) {
  12303. this.onSizeChanged();
  12304. }
  12305. }
  12306. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12307. if (this.onActivate) {
  12308. this.onActivate(camera);
  12309. }
  12310. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12311. if (this._reusable) {
  12312. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12313. }
  12314. };
  12315. PostProcess.prototype.apply = function () {
  12316. if (!this._effect.isReady())
  12317. return null;
  12318. this._engine.enableEffect(this._effect);
  12319. this._engine.setState(false);
  12320. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12321. this._engine.setDepthBuffer(false);
  12322. this._engine.setDepthWrite(false);
  12323. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12324. if (this.onApply) {
  12325. this.onApply(this._effect);
  12326. }
  12327. return this._effect;
  12328. };
  12329. PostProcess.prototype.dispose = function (camera) {
  12330. camera = camera || this._camera;
  12331. if (this._textures.length > 0) {
  12332. for (var i = 0; i < this._textures.length; i++) {
  12333. this._engine._releaseTexture(this._textures.data[i]);
  12334. }
  12335. this._textures.reset();
  12336. }
  12337. camera.detachPostProcess(this);
  12338. var index = camera._postProcesses.indexOf(this);
  12339. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12340. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12341. }
  12342. };
  12343. return PostProcess;
  12344. })();
  12345. BABYLON.PostProcess = PostProcess;
  12346. })(BABYLON || (BABYLON = {}));
  12347. var BABYLON;
  12348. (function (BABYLON) {
  12349. var PostProcessManager = (function () {
  12350. function PostProcessManager(scene) {
  12351. this._vertexDeclaration = [2];
  12352. this._vertexStrideSize = 2 * 4;
  12353. this._scene = scene;
  12354. var vertices = [];
  12355. vertices.push(1, 1);
  12356. vertices.push(-1, 1);
  12357. vertices.push(-1, -1);
  12358. vertices.push(1, -1);
  12359. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12360. var indices = [];
  12361. indices.push(0);
  12362. indices.push(1);
  12363. indices.push(2);
  12364. indices.push(0);
  12365. indices.push(2);
  12366. indices.push(3);
  12367. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12368. }
  12369. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12370. var postProcesses = this._scene.activeCamera._postProcesses;
  12371. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12372. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12373. return false;
  12374. }
  12375. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12376. return true;
  12377. };
  12378. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12379. var postProcesses = this._scene.activeCamera._postProcesses;
  12380. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12381. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12382. return;
  12383. }
  12384. var engine = this._scene.getEngine();
  12385. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12386. if (index < postProcessesTakenIndices.length - 1) {
  12387. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12388. } else {
  12389. if (targetTexture) {
  12390. engine.bindFramebuffer(targetTexture);
  12391. } else {
  12392. engine.restoreDefaultFramebuffer();
  12393. }
  12394. }
  12395. if (doNotPresent) {
  12396. break;
  12397. }
  12398. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12399. if (effect) {
  12400. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12401. engine.draw(true, 0, 6);
  12402. }
  12403. }
  12404. engine.setDepthBuffer(true);
  12405. engine.setDepthWrite(true);
  12406. };
  12407. PostProcessManager.prototype.dispose = function () {
  12408. if (this._vertexBuffer) {
  12409. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12410. this._vertexBuffer = null;
  12411. }
  12412. if (this._indexBuffer) {
  12413. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12414. this._indexBuffer = null;
  12415. }
  12416. };
  12417. return PostProcessManager;
  12418. })();
  12419. BABYLON.PostProcessManager = PostProcessManager;
  12420. })(BABYLON || (BABYLON = {}));
  12421. var __extends = this.__extends || function (d, b) {
  12422. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12423. function __() { this.constructor = d; }
  12424. __.prototype = b.prototype;
  12425. d.prototype = new __();
  12426. };
  12427. var BABYLON;
  12428. (function (BABYLON) {
  12429. var PassPostProcess = (function (_super) {
  12430. __extends(PassPostProcess, _super);
  12431. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12432. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12433. }
  12434. return PassPostProcess;
  12435. })(BABYLON.PostProcess);
  12436. BABYLON.PassPostProcess = PassPostProcess;
  12437. })(BABYLON || (BABYLON = {}));
  12438. var __extends = this.__extends || function (d, b) {
  12439. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12440. function __() { this.constructor = d; }
  12441. __.prototype = b.prototype;
  12442. d.prototype = new __();
  12443. };
  12444. var BABYLON;
  12445. (function (BABYLON) {
  12446. var BlurPostProcess = (function (_super) {
  12447. __extends(BlurPostProcess, _super);
  12448. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12449. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12450. var _this = this;
  12451. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12452. this.direction = direction;
  12453. this.blurWidth = blurWidth;
  12454. this.onApply = function (effect) {
  12455. effect.setFloat2("screenSize", _this.width, _this.height);
  12456. effect.setVector2("direction", _this.direction);
  12457. effect.setFloat("blurWidth", _this.blurWidth);
  12458. };
  12459. }
  12460. return BlurPostProcess;
  12461. })(BABYLON.PostProcess);
  12462. BABYLON.BlurPostProcess = BlurPostProcess;
  12463. })(BABYLON || (BABYLON = {}));
  12464. var __extends = this.__extends || function (d, b) {
  12465. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12466. function __() { this.constructor = d; }
  12467. __.prototype = b.prototype;
  12468. d.prototype = new __();
  12469. };
  12470. var BABYLON;
  12471. (function (BABYLON) {
  12472. var FilterPostProcess = (function (_super) {
  12473. __extends(FilterPostProcess, _super);
  12474. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12475. var _this = this;
  12476. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12477. this.kernelMatrix = kernelMatrix;
  12478. this.onApply = function (effect) {
  12479. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12480. };
  12481. }
  12482. return FilterPostProcess;
  12483. })(BABYLON.PostProcess);
  12484. BABYLON.FilterPostProcess = FilterPostProcess;
  12485. })(BABYLON || (BABYLON = {}));
  12486. var __extends = this.__extends || function (d, b) {
  12487. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12488. function __() { this.constructor = d; }
  12489. __.prototype = b.prototype;
  12490. d.prototype = new __();
  12491. };
  12492. var BABYLON;
  12493. (function (BABYLON) {
  12494. var RefractionPostProcess = (function (_super) {
  12495. __extends(RefractionPostProcess, _super);
  12496. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12497. var _this = this;
  12498. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12499. this.color = color;
  12500. this.depth = depth;
  12501. this.colorLevel = colorLevel;
  12502. this.onActivate = function (cam) {
  12503. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12504. };
  12505. this.onApply = function (effect) {
  12506. effect.setColor3("baseColor", _this.color);
  12507. effect.setFloat("depth", _this.depth);
  12508. effect.setFloat("colorLevel", _this.colorLevel);
  12509. effect.setTexture("refractionSampler", _this._refRexture);
  12510. };
  12511. }
  12512. RefractionPostProcess.prototype.dispose = function (camera) {
  12513. if (this._refRexture) {
  12514. this._refRexture.dispose();
  12515. }
  12516. _super.prototype.dispose.call(this, camera);
  12517. };
  12518. return RefractionPostProcess;
  12519. })(BABYLON.PostProcess);
  12520. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12521. })(BABYLON || (BABYLON = {}));
  12522. var __extends = this.__extends || function (d, b) {
  12523. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12524. function __() { this.constructor = d; }
  12525. __.prototype = b.prototype;
  12526. d.prototype = new __();
  12527. };
  12528. var BABYLON;
  12529. (function (BABYLON) {
  12530. var BlackAndWhitePostProcess = (function (_super) {
  12531. __extends(BlackAndWhitePostProcess, _super);
  12532. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12533. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12534. }
  12535. return BlackAndWhitePostProcess;
  12536. })(BABYLON.PostProcess);
  12537. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12538. })(BABYLON || (BABYLON = {}));
  12539. var __extends = this.__extends || function (d, b) {
  12540. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12541. function __() { this.constructor = d; }
  12542. __.prototype = b.prototype;
  12543. d.prototype = new __();
  12544. };
  12545. var BABYLON;
  12546. (function (BABYLON) {
  12547. var ConvolutionPostProcess = (function (_super) {
  12548. __extends(ConvolutionPostProcess, _super);
  12549. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12550. var _this = this;
  12551. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12552. this.kernel = kernel;
  12553. this.onApply = function (effect) {
  12554. effect.setFloat2("screenSize", _this.width, _this.height);
  12555. effect.setArray("kernel", _this.kernel);
  12556. };
  12557. }
  12558. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12559. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12560. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12561. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12562. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12563. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12564. return ConvolutionPostProcess;
  12565. })(BABYLON.PostProcess);
  12566. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12567. })(BABYLON || (BABYLON = {}));
  12568. var __extends = this.__extends || function (d, b) {
  12569. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12570. function __() { this.constructor = d; }
  12571. __.prototype = b.prototype;
  12572. d.prototype = new __();
  12573. };
  12574. var BABYLON;
  12575. (function (BABYLON) {
  12576. var FxaaPostProcess = (function (_super) {
  12577. __extends(FxaaPostProcess, _super);
  12578. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12579. var _this = this;
  12580. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12581. this.onSizeChanged = function () {
  12582. _this.texelWidth = 1.0 / _this.width;
  12583. _this.texelHeight = 1.0 / _this.height;
  12584. };
  12585. this.onApply = function (effect) {
  12586. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12587. };
  12588. }
  12589. return FxaaPostProcess;
  12590. })(BABYLON.PostProcess);
  12591. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12592. })(BABYLON || (BABYLON = {}));
  12593. var BABYLON;
  12594. (function (BABYLON) {
  12595. var LensFlare = (function () {
  12596. function LensFlare(size, position, color, imgUrl, system) {
  12597. this.size = size;
  12598. this.position = position;
  12599. this.dispose = function () {
  12600. if (this.texture) {
  12601. this.texture.dispose();
  12602. }
  12603. var index = this._system.lensFlares.indexOf(this);
  12604. this._system.lensFlares.splice(index, 1);
  12605. };
  12606. this.color = color || new BABYLON.Color3(1, 1, 1);
  12607. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12608. this._system = system;
  12609. system.lensFlares.push(this);
  12610. }
  12611. return LensFlare;
  12612. })();
  12613. BABYLON.LensFlare = LensFlare;
  12614. })(BABYLON || (BABYLON = {}));
  12615. var BABYLON;
  12616. (function (BABYLON) {
  12617. var LensFlareSystem = (function () {
  12618. function LensFlareSystem(name, emitter, scene) {
  12619. this.name = name;
  12620. this.lensFlares = new Array();
  12621. this.borderLimit = 300;
  12622. this._vertexDeclaration = [2];
  12623. this._vertexStrideSize = 2 * 4;
  12624. this._isEnabled = true;
  12625. this._scene = scene;
  12626. this._emitter = emitter;
  12627. scene.lensFlareSystems.push(this);
  12628. this.meshesSelectionPredicate = function (m) {
  12629. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12630. };
  12631. var vertices = [];
  12632. vertices.push(1, 1);
  12633. vertices.push(-1, 1);
  12634. vertices.push(-1, -1);
  12635. vertices.push(1, -1);
  12636. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12637. var indices = [];
  12638. indices.push(0);
  12639. indices.push(1);
  12640. indices.push(2);
  12641. indices.push(0);
  12642. indices.push(2);
  12643. indices.push(3);
  12644. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12645. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12646. }
  12647. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12648. get: function () {
  12649. return this._isEnabled;
  12650. },
  12651. set: function (value) {
  12652. this._isEnabled = value;
  12653. },
  12654. enumerable: true,
  12655. configurable: true
  12656. });
  12657. LensFlareSystem.prototype.getScene = function () {
  12658. return this._scene;
  12659. };
  12660. LensFlareSystem.prototype.getEmitter = function () {
  12661. return this._emitter;
  12662. };
  12663. LensFlareSystem.prototype.getEmitterPosition = function () {
  12664. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12665. };
  12666. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12667. var position = this.getEmitterPosition();
  12668. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12669. this._positionX = position.x;
  12670. this._positionY = position.y;
  12671. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12672. if (position.z > 0) {
  12673. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12674. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12675. return true;
  12676. }
  12677. }
  12678. return false;
  12679. };
  12680. LensFlareSystem.prototype._isVisible = function () {
  12681. if (!this._isEnabled) {
  12682. return false;
  12683. }
  12684. var emitterPosition = this.getEmitterPosition();
  12685. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12686. var distance = direction.length();
  12687. direction.normalize();
  12688. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12689. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12690. return !pickInfo.hit || pickInfo.distance > distance;
  12691. };
  12692. LensFlareSystem.prototype.render = function () {
  12693. if (!this._effect.isReady())
  12694. return false;
  12695. var engine = this._scene.getEngine();
  12696. var viewport = this._scene.activeCamera.viewport;
  12697. var globalViewport = viewport.toGlobal(engine);
  12698. if (!this.computeEffectivePosition(globalViewport)) {
  12699. return false;
  12700. }
  12701. if (!this._isVisible()) {
  12702. return false;
  12703. }
  12704. var awayX;
  12705. var awayY;
  12706. if (this._positionX < this.borderLimit + globalViewport.x) {
  12707. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12708. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12709. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12710. } else {
  12711. awayX = 0;
  12712. }
  12713. if (this._positionY < this.borderLimit + globalViewport.y) {
  12714. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12715. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12716. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12717. } else {
  12718. awayY = 0;
  12719. }
  12720. var away = (awayX > awayY) ? awayX : awayY;
  12721. if (away > this.borderLimit) {
  12722. away = this.borderLimit;
  12723. }
  12724. var intensity = 1.0 - (away / this.borderLimit);
  12725. if (intensity < 0) {
  12726. return false;
  12727. }
  12728. if (intensity > 1.0) {
  12729. intensity = 1.0;
  12730. }
  12731. var centerX = globalViewport.x + globalViewport.width / 2;
  12732. var centerY = globalViewport.y + globalViewport.height / 2;
  12733. var distX = centerX - this._positionX;
  12734. var distY = centerY - this._positionY;
  12735. engine.enableEffect(this._effect);
  12736. engine.setState(false);
  12737. engine.setDepthBuffer(false);
  12738. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12739. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12740. for (var index = 0; index < this.lensFlares.length; index++) {
  12741. var flare = this.lensFlares[index];
  12742. var x = centerX - (distX * flare.position);
  12743. var y = centerY - (distY * flare.position);
  12744. var cw = flare.size;
  12745. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12746. var cx = 2 * (x / globalViewport.width) - 1.0;
  12747. var cy = 1.0 - 2 * (y / globalViewport.height);
  12748. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12749. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12750. this._effect.setTexture("textureSampler", flare.texture);
  12751. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12752. engine.draw(true, 0, 6);
  12753. }
  12754. engine.setDepthBuffer(true);
  12755. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12756. return true;
  12757. };
  12758. LensFlareSystem.prototype.dispose = function () {
  12759. if (this._vertexBuffer) {
  12760. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12761. this._vertexBuffer = null;
  12762. }
  12763. if (this._indexBuffer) {
  12764. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12765. this._indexBuffer = null;
  12766. }
  12767. while (this.lensFlares.length) {
  12768. this.lensFlares[0].dispose();
  12769. }
  12770. var index = this._scene.lensFlareSystems.indexOf(this);
  12771. this._scene.lensFlareSystems.splice(index, 1);
  12772. };
  12773. return LensFlareSystem;
  12774. })();
  12775. BABYLON.LensFlareSystem = LensFlareSystem;
  12776. })(BABYLON || (BABYLON = {}));
  12777. var BABYLON;
  12778. (function (BABYLON) {
  12779. var IntersectionInfo = (function () {
  12780. function IntersectionInfo(bu, bv, distance) {
  12781. this.bu = bu;
  12782. this.bv = bv;
  12783. this.distance = distance;
  12784. this.faceId = 0;
  12785. }
  12786. return IntersectionInfo;
  12787. })();
  12788. BABYLON.IntersectionInfo = IntersectionInfo;
  12789. var PickingInfo = (function () {
  12790. function PickingInfo() {
  12791. this.hit = false;
  12792. this.distance = 0;
  12793. this.pickedPoint = null;
  12794. this.pickedMesh = null;
  12795. this.bu = 0;
  12796. this.bv = 0;
  12797. this.faceId = -1;
  12798. }
  12799. PickingInfo.prototype.getNormal = function () {
  12800. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12801. return null;
  12802. }
  12803. var indices = this.pickedMesh.getIndices();
  12804. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12805. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12806. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12807. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12808. normal0 = normal0.scale(this.bu);
  12809. normal1 = normal1.scale(this.bv);
  12810. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12811. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12812. };
  12813. PickingInfo.prototype.getTextureCoordinates = function () {
  12814. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12815. return null;
  12816. }
  12817. var indices = this.pickedMesh.getIndices();
  12818. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12819. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12820. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12821. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12822. uv0 = uv0.scale(this.bu);
  12823. uv1 = uv1.scale(this.bv);
  12824. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12825. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12826. };
  12827. return PickingInfo;
  12828. })();
  12829. BABYLON.PickingInfo = PickingInfo;
  12830. })(BABYLON || (BABYLON = {}));
  12831. var BABYLON;
  12832. (function (BABYLON) {
  12833. var FilesInput = (function () {
  12834. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12835. this.engine = p_engine;
  12836. this.canvas = p_canvas;
  12837. this.currentScene = p_scene;
  12838. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12839. this.progressCallback = p_progressCallback;
  12840. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12841. this.textureLoadingCallback = p_textureLoadingCallback;
  12842. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12843. }
  12844. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12845. var _this = this;
  12846. if (p_elementToMonitor) {
  12847. this.elementToMonitor = p_elementToMonitor;
  12848. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12849. _this.drag(e);
  12850. }, false);
  12851. this.elementToMonitor.addEventListener("dragover", function (e) {
  12852. _this.drag(e);
  12853. }, false);
  12854. this.elementToMonitor.addEventListener("drop", function (e) {
  12855. _this.drop(e);
  12856. }, false);
  12857. }
  12858. };
  12859. FilesInput.prototype.renderFunction = function () {
  12860. if (this.additionnalRenderLoopLogicCallback) {
  12861. this.additionnalRenderLoopLogicCallback();
  12862. }
  12863. if (this.currentScene) {
  12864. if (this.textureLoadingCallback) {
  12865. var remaining = this.currentScene.getWaitingItemsCount();
  12866. if (remaining > 0) {
  12867. this.textureLoadingCallback(remaining);
  12868. }
  12869. }
  12870. this.currentScene.render();
  12871. }
  12872. };
  12873. FilesInput.prototype.drag = function (e) {
  12874. e.stopPropagation();
  12875. e.preventDefault();
  12876. };
  12877. FilesInput.prototype.drop = function (eventDrop) {
  12878. eventDrop.stopPropagation();
  12879. eventDrop.preventDefault();
  12880. this.loadFiles(eventDrop);
  12881. };
  12882. FilesInput.prototype.loadFiles = function (event) {
  12883. var _this = this;
  12884. var that = this;
  12885. if (this.startingProcessingFilesCallback)
  12886. this.startingProcessingFilesCallback();
  12887. var sceneFileToLoad;
  12888. var filesToLoad;
  12889. if (event && event.dataTransfer && event.dataTransfer.files) {
  12890. filesToLoad = event.dataTransfer.files;
  12891. }
  12892. if (event && event.target && event.target.files) {
  12893. filesToLoad = event.target.files;
  12894. }
  12895. if (filesToLoad && filesToLoad.length > 0) {
  12896. for (var i = 0; i < filesToLoad.length; i++) {
  12897. switch (filesToLoad[i].type) {
  12898. case "image/jpeg":
  12899. case "image/png":
  12900. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12901. break;
  12902. case "image/targa":
  12903. case "image/vnd.ms-dds":
  12904. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12905. break;
  12906. default:
  12907. 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) {
  12908. sceneFileToLoad = filesToLoad[i];
  12909. }
  12910. break;
  12911. }
  12912. }
  12913. if (sceneFileToLoad) {
  12914. if (this.currentScene) {
  12915. this.engine.stopRenderLoop();
  12916. this.currentScene.dispose();
  12917. }
  12918. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12919. that.currentScene = newScene;
  12920. that.currentScene.executeWhenReady(function () {
  12921. if (that.currentScene.activeCamera) {
  12922. that.currentScene.activeCamera.attachControl(that.canvas);
  12923. }
  12924. if (that.sceneLoadedCallback) {
  12925. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12926. }
  12927. that.engine.runRenderLoop(function () {
  12928. that.renderFunction();
  12929. });
  12930. });
  12931. }, function (progress) {
  12932. if (_this.progressCallback) {
  12933. _this.progressCallback(progress);
  12934. }
  12935. });
  12936. } else {
  12937. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12938. }
  12939. }
  12940. };
  12941. FilesInput.FilesTextures = new Array();
  12942. FilesInput.FilesToLoad = new Array();
  12943. return FilesInput;
  12944. })();
  12945. BABYLON.FilesInput = FilesInput;
  12946. })(BABYLON || (BABYLON = {}));
  12947. var BABYLON;
  12948. (function (BABYLON) {
  12949. var OimoJSPlugin = (function () {
  12950. function OimoJSPlugin() {
  12951. this._registeredMeshes = [];
  12952. /**
  12953. * Update the body position according to the mesh position
  12954. * @param mesh
  12955. */
  12956. this.updateBodyPosition = function (mesh) {
  12957. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12958. var registeredMesh = this._registeredMeshes[index];
  12959. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12960. var body = registeredMesh.body.body;
  12961. var center = mesh.getBoundingInfo().boundingBox.center;
  12962. body.setPosition(center.x, center.y, center.z);
  12963. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12964. return;
  12965. }
  12966. if (registeredMesh.mesh.parent === mesh) {
  12967. mesh.computeWorldMatrix(true);
  12968. registeredMesh.mesh.computeWorldMatrix(true);
  12969. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12970. var absoluteRotation = mesh.rotation;
  12971. body = registeredMesh.body.body;
  12972. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12973. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12974. return;
  12975. }
  12976. }
  12977. };
  12978. }
  12979. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12980. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12981. };
  12982. OimoJSPlugin.prototype.initialize = function (iterations) {
  12983. this._world = new OIMO.World();
  12984. this._world.clear();
  12985. };
  12986. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12987. this._world.gravity = gravity;
  12988. };
  12989. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12990. var body = null;
  12991. this.unregisterMesh(mesh);
  12992. mesh.computeWorldMatrix(true);
  12993. switch (impostor) {
  12994. case BABYLON.PhysicsEngine.SphereImpostor:
  12995. var bbox = mesh.getBoundingInfo().boundingBox;
  12996. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12997. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12998. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12999. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13000. var deltaPosition = mesh.position.subtract(bbox.center);
  13001. body = new OIMO.Body({
  13002. type: 'sphere',
  13003. size: [size],
  13004. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13005. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13006. move: options.mass != 0,
  13007. config: [options.mass, options.friction, options.restitution],
  13008. world: this._world
  13009. });
  13010. this._registeredMeshes.push({
  13011. mesh: mesh,
  13012. body: body,
  13013. delta: deltaPosition
  13014. });
  13015. break;
  13016. case BABYLON.PhysicsEngine.PlaneImpostor:
  13017. case BABYLON.PhysicsEngine.BoxImpostor:
  13018. bbox = mesh.getBoundingInfo().boundingBox;
  13019. var min = bbox.minimumWorld;
  13020. var max = bbox.maximumWorld;
  13021. var box = max.subtract(min);
  13022. var sizeX = this._checkWithEpsilon(box.x);
  13023. var sizeY = this._checkWithEpsilon(box.y);
  13024. var sizeZ = this._checkWithEpsilon(box.z);
  13025. var deltaPosition = mesh.position.subtract(bbox.center);
  13026. body = new OIMO.Body({
  13027. type: 'box',
  13028. size: [sizeX, sizeY, sizeZ],
  13029. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13030. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13031. move: options.mass != 0,
  13032. config: [options.mass, options.friction, options.restitution],
  13033. world: this._world
  13034. });
  13035. this._registeredMeshes.push({
  13036. mesh: mesh,
  13037. body: body,
  13038. delta: deltaPosition
  13039. });
  13040. break;
  13041. }
  13042. return body;
  13043. };
  13044. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13045. var types = [], sizes = [], positions = [], rotations = [];
  13046. var initialMesh = parts[0].mesh;
  13047. for (var index = 0; index < parts.length; index++) {
  13048. var part = parts[index];
  13049. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13050. types.push(bodyParameters.type);
  13051. sizes.push.apply(sizes, bodyParameters.size);
  13052. positions.push.apply(positions, bodyParameters.pos);
  13053. rotations.push.apply(rotations, bodyParameters.rot);
  13054. }
  13055. var body = new OIMO.Body({
  13056. type: types,
  13057. size: sizes,
  13058. pos: positions,
  13059. rot: rotations,
  13060. move: options.mass != 0,
  13061. config: [options.mass, options.friction, options.restitution],
  13062. world: this._world
  13063. });
  13064. this._registeredMeshes.push({
  13065. mesh: initialMesh,
  13066. body: body
  13067. });
  13068. return body;
  13069. };
  13070. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13071. var bodyParameters = null;
  13072. var mesh = part.mesh;
  13073. switch (part.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. bodyParameters = {
  13081. type: 'sphere',
  13082. /* bug with oimo : sphere needs 3 sizes in this case */
  13083. size: [size, -1, -1],
  13084. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13085. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13086. };
  13087. break;
  13088. case BABYLON.PhysicsEngine.PlaneImpostor:
  13089. case BABYLON.PhysicsEngine.BoxImpostor:
  13090. bbox = mesh.getBoundingInfo().boundingBox;
  13091. var min = bbox.minimumWorld;
  13092. var max = bbox.maximumWorld;
  13093. var box = max.subtract(min);
  13094. var sizeX = this._checkWithEpsilon(box.x);
  13095. var sizeY = this._checkWithEpsilon(box.y);
  13096. var sizeZ = this._checkWithEpsilon(box.z);
  13097. var relativePosition = mesh.position;
  13098. bodyParameters = {
  13099. type: 'box',
  13100. size: [sizeX, sizeY, sizeZ],
  13101. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13102. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13103. };
  13104. break;
  13105. }
  13106. return bodyParameters;
  13107. };
  13108. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13109. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13110. var registeredMesh = this._registeredMeshes[index];
  13111. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13112. if (registeredMesh.body) {
  13113. this._world.removeRigidBody(registeredMesh.body.body);
  13114. this._unbindBody(registeredMesh.body);
  13115. }
  13116. this._registeredMeshes.splice(index, 1);
  13117. return;
  13118. }
  13119. }
  13120. };
  13121. OimoJSPlugin.prototype._unbindBody = function (body) {
  13122. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13123. var registeredMesh = this._registeredMeshes[index];
  13124. if (registeredMesh.body === body) {
  13125. registeredMesh.body = null;
  13126. }
  13127. }
  13128. };
  13129. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13130. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13131. var registeredMesh = this._registeredMeshes[index];
  13132. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13133. var mass = registeredMesh.body.body.massInfo.mass;
  13134. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13135. return;
  13136. }
  13137. }
  13138. };
  13139. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13140. var body1 = null, body2 = null;
  13141. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13142. var registeredMesh = this._registeredMeshes[index];
  13143. if (registeredMesh.mesh === mesh1) {
  13144. body1 = registeredMesh.body.body;
  13145. } else if (registeredMesh.mesh === mesh2) {
  13146. body2 = registeredMesh.body.body;
  13147. }
  13148. }
  13149. if (!body1 || !body2) {
  13150. return false;
  13151. }
  13152. if (!options) {
  13153. options = {};
  13154. }
  13155. new OIMO.Link({
  13156. type: options.type,
  13157. body1: body1,
  13158. body2: body2,
  13159. min: options.min,
  13160. max: options.max,
  13161. axe1: options.axe1,
  13162. axe2: options.axe2,
  13163. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13164. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13165. collision: options.collision,
  13166. spring: options.spring,
  13167. world: this._world
  13168. });
  13169. return true;
  13170. };
  13171. OimoJSPlugin.prototype.dispose = function () {
  13172. this._world.clear();
  13173. while (this._registeredMeshes.length) {
  13174. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13175. }
  13176. };
  13177. OimoJSPlugin.prototype.isSupported = function () {
  13178. return OIMO !== undefined;
  13179. };
  13180. OimoJSPlugin.prototype._getLastShape = function (body) {
  13181. var lastShape = body.shapes;
  13182. while (lastShape.next) {
  13183. lastShape = lastShape.next;
  13184. }
  13185. return lastShape;
  13186. };
  13187. OimoJSPlugin.prototype.runOneStep = function (time) {
  13188. this._world.step();
  13189. var i = this._registeredMeshes.length;
  13190. var m;
  13191. while (i--) {
  13192. var body = this._registeredMeshes[i].body.body;
  13193. var mesh = this._registeredMeshes[i].mesh;
  13194. var delta = this._registeredMeshes[i].delta;
  13195. if (!body.sleeping) {
  13196. if (body.shapes.next) {
  13197. var parentShape = this._getLastShape(body);
  13198. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13199. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13200. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13201. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13202. if (!mesh.rotationQuaternion) {
  13203. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13204. }
  13205. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13206. } else {
  13207. m = body.getMatrix();
  13208. mtx = BABYLON.Matrix.FromArray(m);
  13209. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13210. if (!delta) {
  13211. mesh.position.x = bodyX;
  13212. mesh.position.y = bodyY;
  13213. mesh.position.z = bodyZ;
  13214. } else {
  13215. mesh.position.x = bodyX + delta.x;
  13216. mesh.position.y = bodyY + delta.y;
  13217. mesh.position.z = bodyZ + delta.z;
  13218. }
  13219. if (!mesh.rotationQuaternion) {
  13220. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13221. }
  13222. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13223. }
  13224. }
  13225. }
  13226. };
  13227. return OimoJSPlugin;
  13228. })();
  13229. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13230. })(BABYLON || (BABYLON = {}));
  13231. var BABYLON;
  13232. (function (BABYLON) {
  13233. var PhysicsEngine = (function () {
  13234. function PhysicsEngine(plugin) {
  13235. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13236. }
  13237. PhysicsEngine.prototype._initialize = function (gravity) {
  13238. this._currentPlugin.initialize();
  13239. this._setGravity(gravity);
  13240. };
  13241. PhysicsEngine.prototype._runOneStep = function (delta) {
  13242. if (delta > 0.1) {
  13243. delta = 0.1;
  13244. } else if (delta <= 0) {
  13245. delta = 1.0 / 60.0;
  13246. }
  13247. this._currentPlugin.runOneStep(delta);
  13248. };
  13249. PhysicsEngine.prototype._setGravity = function (gravity) {
  13250. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13251. this._currentPlugin.setGravity(this.gravity);
  13252. };
  13253. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13254. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13255. };
  13256. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13257. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13258. };
  13259. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13260. this._currentPlugin.unregisterMesh(mesh);
  13261. };
  13262. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13263. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13264. };
  13265. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13266. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13267. };
  13268. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13269. this._currentPlugin.updateBodyPosition(mesh);
  13270. };
  13271. PhysicsEngine.prototype.dispose = function () {
  13272. this._currentPlugin.dispose();
  13273. };
  13274. PhysicsEngine.prototype.isSupported = function () {
  13275. return this._currentPlugin.isSupported();
  13276. };
  13277. PhysicsEngine.NoImpostor = 0;
  13278. PhysicsEngine.SphereImpostor = 1;
  13279. PhysicsEngine.BoxImpostor = 2;
  13280. PhysicsEngine.PlaneImpostor = 3;
  13281. PhysicsEngine.CompoundImpostor = 4;
  13282. PhysicsEngine.MeshImpostor = 4;
  13283. PhysicsEngine.CapsuleImpostor = 5;
  13284. PhysicsEngine.ConeImpostor = 6;
  13285. PhysicsEngine.CylinderImpostor = 7;
  13286. PhysicsEngine.ConvexHullImpostor = 8;
  13287. PhysicsEngine.Epsilon = 0.001;
  13288. return PhysicsEngine;
  13289. })();
  13290. BABYLON.PhysicsEngine = PhysicsEngine;
  13291. })(BABYLON || (BABYLON = {}));
  13292. var BABYLON;
  13293. (function (BABYLON) {
  13294. var serializeLight = function (light) {
  13295. var serializationObject = {};
  13296. serializationObject.name = light.name;
  13297. serializationObject.id = light.id;
  13298. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13299. if (light instanceof BABYLON.PointLight) {
  13300. serializationObject.type = 0;
  13301. serializationObject.position = light.position.asArray();
  13302. } else if (light instanceof BABYLON.DirectionalLight) {
  13303. serializationObject.type = 1;
  13304. var directionalLight = light;
  13305. serializationObject.position = directionalLight.position.asArray();
  13306. serializationObject.direction = directionalLight.direction.asArray();
  13307. } else if (light instanceof BABYLON.SpotLight) {
  13308. serializationObject.type = 2;
  13309. var spotLight = light;
  13310. serializationObject.position = spotLight.position.asArray();
  13311. serializationObject.direction = spotLight.position.asArray();
  13312. serializationObject.angle = spotLight.angle;
  13313. serializationObject.exponent = spotLight.exponent;
  13314. } else if (light instanceof BABYLON.HemisphericLight) {
  13315. serializationObject.type = 3;
  13316. var hemisphericLight = light;
  13317. serializationObject.direction = hemisphericLight.direction.asArray();
  13318. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13319. }
  13320. if (light.intensity) {
  13321. serializationObject.intensity = light.intensity;
  13322. }
  13323. serializationObject.range = light.range;
  13324. serializationObject.diffuse = light.diffuse.asArray();
  13325. serializationObject.specular = light.specular.asArray();
  13326. return serializationObject;
  13327. };
  13328. var serializeFresnelParameter = function (fresnelParameter) {
  13329. var serializationObject = {};
  13330. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13331. serializationObject.leftColor = fresnelParameter.leftColor;
  13332. serializationObject.rightColor = fresnelParameter.rightColor;
  13333. serializationObject.bias = fresnelParameter.bias;
  13334. serializationObject.power = fresnelParameter.power;
  13335. return serializationObject;
  13336. };
  13337. var serializeCamera = function (camera) {
  13338. var serializationObject = {};
  13339. serializationObject.name = camera.name;
  13340. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13341. serializationObject.id = camera.id;
  13342. serializationObject.position = camera.position.asArray();
  13343. if (camera.parent) {
  13344. serializationObject.parentId = camera.parent.id;
  13345. }
  13346. serializationObject.rotation = camera.rotation.asArray();
  13347. if (camera.lockedTarget && camera.lockedTarget.id) {
  13348. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13349. }
  13350. serializationObject.fov = camera.fov;
  13351. serializationObject.minZ = camera.minZ;
  13352. serializationObject.maxZ = camera.maxZ;
  13353. serializationObject.speed = camera.speed;
  13354. serializationObject.inertia = camera.inertia;
  13355. serializationObject.checkCollisions = camera.checkCollisions;
  13356. serializationObject.applyGravity = camera.applyGravity;
  13357. if (camera.ellipsoid) {
  13358. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13359. }
  13360. appendAnimations(camera, serializationObject);
  13361. serializationObject.layerMask = camera.layerMask;
  13362. return serializationObject;
  13363. };
  13364. var appendAnimations = function (source, destination) {
  13365. if (source.animations) {
  13366. destination.animations = [];
  13367. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13368. var animation = source.animations[animationIndex];
  13369. destination.animations.push(serializeAnimation(animation));
  13370. }
  13371. }
  13372. };
  13373. var serializeAnimation = function (animation) {
  13374. var serializationObject = {};
  13375. serializationObject.name = animation.name;
  13376. serializationObject.property = animation.targetProperty;
  13377. serializationObject.framePerSecond = animation.framePerSecond;
  13378. serializationObject.dataType = animation.dataType;
  13379. serializationObject.loopBehavior = animation.loopMode;
  13380. var dataType = animation.dataType;
  13381. serializationObject.keys = [];
  13382. var keys = animation.getKeys();
  13383. for (var index = 0; index < keys.length; index++) {
  13384. var animationKey = keys[index];
  13385. var key = {};
  13386. key.frame = animationKey.frame;
  13387. switch (dataType) {
  13388. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13389. key.values = [animationKey.value];
  13390. break;
  13391. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13392. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13393. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13394. key.values = animationKey.value.asArray();
  13395. break;
  13396. }
  13397. serializationObject.keys.push(key);
  13398. }
  13399. return serializationObject;
  13400. };
  13401. var serializeMultiMaterial = function (material) {
  13402. var serializationObject = {};
  13403. serializationObject.name = material.name;
  13404. serializationObject.id = material.id;
  13405. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13406. serializationObject.materials = [];
  13407. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13408. var subMat = material.subMaterials[matIndex];
  13409. if (subMat) {
  13410. serializationObject.materials.push(subMat.id);
  13411. } else {
  13412. serializationObject.materials.push(null);
  13413. }
  13414. }
  13415. return serializationObject;
  13416. };
  13417. var serializeMaterial = function (material) {
  13418. var serializationObject = {};
  13419. serializationObject.name = material.name;
  13420. serializationObject.ambient = material.ambientColor.asArray();
  13421. serializationObject.diffuse = material.diffuseColor.asArray();
  13422. serializationObject.specular = material.specularColor.asArray();
  13423. serializationObject.specularPower = material.specularPower;
  13424. serializationObject.emissive = material.emissiveColor.asArray();
  13425. serializationObject.alpha = material.alpha;
  13426. serializationObject.id = material.id;
  13427. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13428. serializationObject.backFaceCulling = material.backFaceCulling;
  13429. if (material.diffuseTexture) {
  13430. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13431. }
  13432. if (material.diffuseFresnelParameters) {
  13433. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13434. }
  13435. if (material.ambientTexture) {
  13436. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13437. }
  13438. if (material.opacityTexture) {
  13439. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13440. }
  13441. if (material.opacityFresnelParameters) {
  13442. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13443. }
  13444. if (material.reflectionTexture) {
  13445. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13446. }
  13447. if (material.reflectionFresnelParameters) {
  13448. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13449. }
  13450. if (material.emissiveTexture) {
  13451. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13452. }
  13453. if (material.emissiveFresnelParameters) {
  13454. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13455. }
  13456. if (material.specularTexture) {
  13457. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13458. }
  13459. if (material.bumpTexture) {
  13460. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13461. }
  13462. return serializationObject;
  13463. };
  13464. var serializeTexture = function (texture) {
  13465. var serializationObject = {};
  13466. if (!texture.name) {
  13467. return null;
  13468. }
  13469. if (texture instanceof BABYLON.CubeTexture) {
  13470. serializationObject.name = texture.name;
  13471. serializationObject.hasAlpha = texture.hasAlpha;
  13472. serializationObject.level = texture.level;
  13473. serializationObject.coordinatesMode = texture.coordinatesMode;
  13474. return serializationObject;
  13475. }
  13476. if (texture instanceof BABYLON.MirrorTexture) {
  13477. var mirrorTexture = texture;
  13478. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13479. serializationObject.renderList = [];
  13480. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13481. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13482. }
  13483. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13484. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13485. var renderTargetTexture = texture;
  13486. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13487. serializationObject.renderList = [];
  13488. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13489. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13490. }
  13491. }
  13492. var regularTexture = texture;
  13493. serializationObject.name = texture.name;
  13494. serializationObject.hasAlpha = texture.hasAlpha;
  13495. serializationObject.level = texture.level;
  13496. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13497. serializationObject.coordinatesMode = texture.coordinatesMode;
  13498. serializationObject.uOffset = regularTexture.uOffset;
  13499. serializationObject.vOffset = regularTexture.vOffset;
  13500. serializationObject.uScale = regularTexture.uScale;
  13501. serializationObject.vScale = regularTexture.vScale;
  13502. serializationObject.uAng = regularTexture.uAng;
  13503. serializationObject.vAng = regularTexture.vAng;
  13504. serializationObject.wAng = regularTexture.wAng;
  13505. serializationObject.wrapU = texture.wrapU;
  13506. serializationObject.wrapV = texture.wrapV;
  13507. appendAnimations(texture, serializationObject);
  13508. return serializationObject;
  13509. };
  13510. var serializeSkeleton = function (skeleton) {
  13511. var serializationObject = {};
  13512. serializationObject.name = skeleton.name;
  13513. serializationObject.id = skeleton.id;
  13514. serializationObject.bones = [];
  13515. for (var index = 0; index < skeleton.bones.length; index++) {
  13516. var bone = skeleton.bones[index];
  13517. var serializedBone = {
  13518. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13519. name: bone.name,
  13520. matrix: bone.getLocalMatrix().toArray()
  13521. };
  13522. serializationObject.bones.push(serializedBone);
  13523. if (bone.animations && bone.animations.length > 0) {
  13524. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13525. }
  13526. }
  13527. return serializationObject;
  13528. };
  13529. var serializeParticleSystem = function (particleSystem) {
  13530. var serializationObject = {};
  13531. serializationObject.emitterId = particleSystem.emitter.id;
  13532. serializationObject.capacity = particleSystem.getCapacity();
  13533. if (particleSystem.particleTexture) {
  13534. serializationObject.textureName = particleSystem.particleTexture.name;
  13535. }
  13536. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13537. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13538. serializationObject.minSize = particleSystem.minSize;
  13539. serializationObject.maxSize = particleSystem.maxSize;
  13540. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13541. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13542. serializationObject.emitRate = particleSystem.emitRate;
  13543. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13544. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13545. serializationObject.gravity = particleSystem.gravity.asArray();
  13546. serializationObject.direction1 = particleSystem.direction1.asArray();
  13547. serializationObject.direction2 = particleSystem.direction2.asArray();
  13548. serializationObject.color1 = particleSystem.color1.asArray();
  13549. serializationObject.color2 = particleSystem.color2.asArray();
  13550. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13551. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13552. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13553. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13554. serializationObject.blendMode = particleSystem.blendMode;
  13555. return serializationObject;
  13556. };
  13557. var serializeLensFlareSystem = function (lensFlareSystem) {
  13558. var serializationObject = {};
  13559. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13560. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13561. serializationObject.flares = [];
  13562. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13563. var flare = lensFlareSystem.lensFlares[index];
  13564. serializationObject.flares.push({
  13565. size: flare.size,
  13566. position: flare.position,
  13567. color: flare.color.asArray(),
  13568. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13569. });
  13570. }
  13571. return serializationObject;
  13572. };
  13573. var serializeShadowGenerator = function (light) {
  13574. var serializationObject = {};
  13575. var shadowGenerator = light.getShadowGenerator();
  13576. serializationObject.lightId = light.id;
  13577. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13578. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13579. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13580. serializationObject.renderList = [];
  13581. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13582. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13583. serializationObject.renderList.push(mesh.id);
  13584. }
  13585. return serializationObject;
  13586. };
  13587. var serializedGeometries = [];
  13588. var serializeGeometry = function (geometry, serializationGeometries) {
  13589. if (serializedGeometries[geometry.id]) {
  13590. return;
  13591. }
  13592. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13593. serializationGeometries.boxes.push(serializeBox(geometry));
  13594. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13595. serializationGeometries.spheres.push(serializeSphere(geometry));
  13596. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13597. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13598. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13599. serializationGeometries.toruses.push(serializeTorus(geometry));
  13600. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13601. serializationGeometries.grounds.push(serializeGround(geometry));
  13602. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13603. serializationGeometries.planes.push(serializePlane(geometry));
  13604. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13605. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13606. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13607. throw new Error("Unknow primitive type");
  13608. } else {
  13609. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13610. }
  13611. serializedGeometries[geometry.id] = true;
  13612. };
  13613. var serializeGeometryBase = function (geometry) {
  13614. var serializationObject = {};
  13615. serializationObject.id = geometry.id;
  13616. if (BABYLON.Tags.HasTags(geometry)) {
  13617. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13618. }
  13619. return serializationObject;
  13620. };
  13621. var serializeVertexData = function (vertexData) {
  13622. var serializationObject = serializeGeometryBase(vertexData);
  13623. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13624. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13625. }
  13626. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13627. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13628. }
  13629. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13630. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13631. }
  13632. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13633. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13634. }
  13635. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13636. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13637. }
  13638. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13639. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13640. serializationObject.matricesIndices._isExpanded = true;
  13641. }
  13642. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13643. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13644. }
  13645. serializationObject.indices = vertexData.getIndices();
  13646. return serializationObject;
  13647. };
  13648. var serializePrimitive = function (primitive) {
  13649. var serializationObject = serializeGeometryBase(primitive);
  13650. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13651. return serializationObject;
  13652. };
  13653. var serializeBox = function (box) {
  13654. var serializationObject = serializePrimitive(box);
  13655. serializationObject.size = box.size;
  13656. return serializationObject;
  13657. };
  13658. var serializeSphere = function (sphere) {
  13659. var serializationObject = serializePrimitive(sphere);
  13660. serializationObject.segments = sphere.segments;
  13661. serializationObject.diameter = sphere.diameter;
  13662. return serializationObject;
  13663. };
  13664. var serializeCylinder = function (cylinder) {
  13665. var serializationObject = serializePrimitive(cylinder);
  13666. serializationObject.height = cylinder.height;
  13667. serializationObject.diameterTop = cylinder.diameterTop;
  13668. serializationObject.diameterBottom = cylinder.diameterBottom;
  13669. serializationObject.tessellation = cylinder.tessellation;
  13670. return serializationObject;
  13671. };
  13672. var serializeTorus = function (torus) {
  13673. var serializationObject = serializePrimitive(torus);
  13674. serializationObject.diameter = torus.diameter;
  13675. serializationObject.thickness = torus.thickness;
  13676. serializationObject.tessellation = torus.tessellation;
  13677. return serializationObject;
  13678. };
  13679. var serializeGround = function (ground) {
  13680. var serializationObject = serializePrimitive(ground);
  13681. serializationObject.width = ground.width;
  13682. serializationObject.height = ground.height;
  13683. serializationObject.subdivisions = ground.subdivisions;
  13684. return serializationObject;
  13685. };
  13686. var serializePlane = function (plane) {
  13687. var serializationObject = serializePrimitive(plane);
  13688. serializationObject.size = plane.size;
  13689. return serializationObject;
  13690. };
  13691. var serializeTorusKnot = function (torusKnot) {
  13692. var serializationObject = serializePrimitive(torusKnot);
  13693. serializationObject.radius = torusKnot.radius;
  13694. serializationObject.tube = torusKnot.tube;
  13695. serializationObject.radialSegments = torusKnot.radialSegments;
  13696. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13697. serializationObject.p = torusKnot.p;
  13698. serializationObject.q = torusKnot.q;
  13699. return serializationObject;
  13700. };
  13701. var serializeMesh = function (mesh, serializationScene) {
  13702. var serializationObject = {};
  13703. serializationObject.name = mesh.name;
  13704. serializationObject.id = mesh.id;
  13705. if (BABYLON.Tags.HasTags(mesh)) {
  13706. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13707. }
  13708. serializationObject.position = mesh.position.asArray();
  13709. if (mesh.rotationQuaternion) {
  13710. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13711. } else if (mesh.rotation) {
  13712. serializationObject.rotation = mesh.rotation.asArray();
  13713. }
  13714. serializationObject.scaling = mesh.scaling.asArray();
  13715. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13716. serializationObject.isEnabled = mesh.isEnabled();
  13717. serializationObject.isVisible = mesh.isVisible;
  13718. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13719. serializationObject.pickable = mesh.isPickable;
  13720. serializationObject.receiveShadows = mesh.receiveShadows;
  13721. serializationObject.billboardMode = mesh.billboardMode;
  13722. serializationObject.visibility = mesh.visibility;
  13723. serializationObject.checkCollisions = mesh.checkCollisions;
  13724. if (mesh.parent) {
  13725. serializationObject.parentId = mesh.parent.id;
  13726. }
  13727. var geometry = mesh._geometry;
  13728. if (geometry) {
  13729. var geometryId = geometry.id;
  13730. serializationObject.geometryId = geometryId;
  13731. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13732. serializeGeometry(geometry, serializationScene.geometries);
  13733. }
  13734. serializationObject.subMeshes = [];
  13735. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13736. var subMesh = mesh.subMeshes[subIndex];
  13737. serializationObject.subMeshes.push({
  13738. materialIndex: subMesh.materialIndex,
  13739. verticesStart: subMesh.verticesStart,
  13740. verticesCount: subMesh.verticesCount,
  13741. indexStart: subMesh.indexStart,
  13742. indexCount: subMesh.indexCount
  13743. });
  13744. }
  13745. }
  13746. if (mesh.material) {
  13747. serializationObject.materialId = mesh.material.id;
  13748. } else {
  13749. mesh.material = null;
  13750. }
  13751. if (mesh.skeleton) {
  13752. serializationObject.skeletonId = mesh.skeleton.id;
  13753. }
  13754. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13755. serializationObject.physicsMass = mesh.getPhysicsMass();
  13756. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13757. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13758. switch (mesh.getPhysicsImpostor()) {
  13759. case BABYLON.PhysicsEngine.BoxImpostor:
  13760. serializationObject.physicsImpostor = 1;
  13761. break;
  13762. case BABYLON.PhysicsEngine.SphereImpostor:
  13763. serializationObject.physicsImpostor = 2;
  13764. break;
  13765. }
  13766. }
  13767. serializationObject.instances = [];
  13768. for (var index = 0; index < mesh.instances.length; index++) {
  13769. var instance = mesh.instances[index];
  13770. var serializationInstance = {
  13771. name: instance.name,
  13772. position: instance.position,
  13773. rotation: instance.rotation,
  13774. rotationQuaternion: instance.rotationQuaternion,
  13775. scaling: instance.scaling
  13776. };
  13777. serializationObject.instances.push(serializationInstance);
  13778. appendAnimations(instance, serializationInstance);
  13779. }
  13780. appendAnimations(mesh, serializationObject);
  13781. serializationObject.layerMask = mesh.layerMask;
  13782. return serializationObject;
  13783. };
  13784. var SceneSerializer = (function () {
  13785. function SceneSerializer() {
  13786. }
  13787. SceneSerializer.Serialize = function (scene) {
  13788. var serializationObject = {};
  13789. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13790. serializationObject.autoClear = scene.autoClear;
  13791. serializationObject.clearColor = scene.clearColor.asArray();
  13792. serializationObject.ambientColor = scene.ambientColor.asArray();
  13793. serializationObject.gravity = scene.gravity.asArray();
  13794. if (scene.fogMode && scene.fogMode !== 0) {
  13795. serializationObject.fogMode = scene.fogMode;
  13796. serializationObject.fogColor = scene.fogColor.asArray();
  13797. serializationObject.fogStart = scene.fogStart;
  13798. serializationObject.fogEnd = scene.fogEnd;
  13799. serializationObject.fogDensity = scene.fogDensity;
  13800. }
  13801. serializationObject.lights = [];
  13802. for (var index = 0; index < scene.lights.length; index++) {
  13803. var light = scene.lights[index];
  13804. serializationObject.lights.push(serializeLight(light));
  13805. }
  13806. serializationObject.cameras = [];
  13807. for (index = 0; index < scene.cameras.length; index++) {
  13808. var camera = scene.cameras[index];
  13809. if (camera instanceof BABYLON.FreeCamera) {
  13810. serializationObject.cameras.push(serializeCamera(camera));
  13811. }
  13812. }
  13813. if (scene.activeCamera) {
  13814. serializationObject.activeCameraID = scene.activeCamera.id;
  13815. }
  13816. serializationObject.materials = [];
  13817. serializationObject.multiMaterials = [];
  13818. for (index = 0; index < scene.materials.length; index++) {
  13819. var material = scene.materials[index];
  13820. if (material instanceof BABYLON.StandardMaterial) {
  13821. serializationObject.materials.push(serializeMaterial(material));
  13822. } else if (material instanceof BABYLON.MultiMaterial) {
  13823. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13824. }
  13825. }
  13826. serializationObject.skeletons = [];
  13827. for (index = 0; index < scene.skeletons.length; index++) {
  13828. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13829. }
  13830. serializationObject.geometries = {};
  13831. serializationObject.geometries.boxes = [];
  13832. serializationObject.geometries.spheres = [];
  13833. serializationObject.geometries.cylinders = [];
  13834. serializationObject.geometries.toruses = [];
  13835. serializationObject.geometries.grounds = [];
  13836. serializationObject.geometries.planes = [];
  13837. serializationObject.geometries.torusKnots = [];
  13838. serializationObject.geometries.vertexData = [];
  13839. serializedGeometries = [];
  13840. var geometries = scene.getGeometries();
  13841. for (var index = 0; index < geometries.length; index++) {
  13842. var geometry = geometries[index];
  13843. if (geometry.isReady()) {
  13844. serializeGeometry(geometry, serializationObject.geometries);
  13845. }
  13846. }
  13847. serializationObject.meshes = [];
  13848. for (index = 0; index < scene.meshes.length; index++) {
  13849. var abstractMesh = scene.meshes[index];
  13850. if (abstractMesh instanceof BABYLON.Mesh) {
  13851. var mesh = abstractMesh;
  13852. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13853. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13854. }
  13855. }
  13856. }
  13857. serializationObject.particleSystems = [];
  13858. for (index = 0; index < scene.particleSystems.length; index++) {
  13859. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13860. }
  13861. serializationObject.lensFlareSystems = [];
  13862. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13863. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13864. }
  13865. serializationObject.shadowGenerators = [];
  13866. for (index = 0; index < scene.lights.length; index++) {
  13867. light = scene.lights[index];
  13868. if (light.getShadowGenerator()) {
  13869. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13870. }
  13871. }
  13872. return serializationObject;
  13873. };
  13874. return SceneSerializer;
  13875. })();
  13876. BABYLON.SceneSerializer = SceneSerializer;
  13877. })(BABYLON || (BABYLON = {}));
  13878. var BABYLON;
  13879. (function (BABYLON) {
  13880. var SceneLoader = (function () {
  13881. function SceneLoader() {
  13882. }
  13883. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13884. get: function () {
  13885. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13886. },
  13887. set: function (value) {
  13888. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13889. },
  13890. enumerable: true,
  13891. configurable: true
  13892. });
  13893. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13894. get: function () {
  13895. return SceneLoader._ShowLoadingScreen;
  13896. },
  13897. set: function (value) {
  13898. SceneLoader._ShowLoadingScreen = value;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13904. var dotPosition = sceneFilename.lastIndexOf(".");
  13905. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13906. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13907. var plugin = this._registeredPlugins[index];
  13908. if (plugin.extensions.indexOf(extension) !== -1) {
  13909. return plugin;
  13910. }
  13911. }
  13912. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13913. };
  13914. SceneLoader.RegisterPlugin = function (plugin) {
  13915. plugin.extensions = plugin.extensions.toLowerCase();
  13916. SceneLoader._registeredPlugins.push(plugin);
  13917. };
  13918. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13919. var _this = this;
  13920. var manifestChecked = function (success) {
  13921. scene.database = database;
  13922. var plugin = _this._getPluginForFilename(sceneFilename);
  13923. var importMeshFromData = function (data) {
  13924. var meshes = [];
  13925. var particleSystems = [];
  13926. var skeletons = [];
  13927. try {
  13928. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13929. if (onerror) {
  13930. onerror(scene);
  13931. }
  13932. return;
  13933. }
  13934. } catch (e) {
  13935. if (onerror) {
  13936. onerror(scene);
  13937. }
  13938. return;
  13939. }
  13940. if (onsuccess) {
  13941. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13942. onsuccess(meshes, particleSystems, skeletons);
  13943. }
  13944. };
  13945. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13946. importMeshFromData(sceneFilename.substr(5));
  13947. return;
  13948. }
  13949. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13950. importMeshFromData(data);
  13951. }, progressCallBack, database);
  13952. };
  13953. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13954. };
  13955. /**
  13956. * Load a scene
  13957. * @param rootUrl a string that defines the root url for scene and resources
  13958. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13959. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13960. */
  13961. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13962. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13963. };
  13964. /**
  13965. * Append a scene
  13966. * @param rootUrl a string that defines the root url for scene and resources
  13967. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13968. * @param scene is the instance of BABYLON.Scene to append to
  13969. */
  13970. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13971. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13972. var database;
  13973. if (SceneLoader.ShowLoadingScreen) {
  13974. scene.getEngine().displayLoadingUI();
  13975. }
  13976. var loadSceneFromData = function (data) {
  13977. scene.database = database;
  13978. if (!plugin.load(scene, data, rootUrl)) {
  13979. if (onerror) {
  13980. onerror(scene);
  13981. }
  13982. scene.getEngine().hideLoadingUI();
  13983. return;
  13984. }
  13985. if (onsuccess) {
  13986. onsuccess(scene);
  13987. }
  13988. if (SceneLoader.ShowLoadingScreen) {
  13989. scene.executeWhenReady(function () {
  13990. scene.getEngine().hideLoadingUI();
  13991. });
  13992. }
  13993. };
  13994. var manifestChecked = function (success) {
  13995. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13996. };
  13997. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13998. loadSceneFromData(sceneFilename.substr(5));
  13999. return;
  14000. }
  14001. if (rootUrl.indexOf("file:") === -1) {
  14002. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14003. } else {
  14004. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14005. }
  14006. };
  14007. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14008. SceneLoader._ShowLoadingScreen = true;
  14009. SceneLoader._registeredPlugins = new Array();
  14010. return SceneLoader;
  14011. })();
  14012. BABYLON.SceneLoader = SceneLoader;
  14013. ;
  14014. })(BABYLON || (BABYLON = {}));
  14015. var BABYLON;
  14016. (function (BABYLON) {
  14017. (function (Internals) {
  14018. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14019. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14020. texture.name = parsedTexture.name;
  14021. texture.hasAlpha = parsedTexture.hasAlpha;
  14022. texture.level = parsedTexture.level;
  14023. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14024. return texture;
  14025. };
  14026. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14027. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14028. return null;
  14029. }
  14030. if (parsedTexture.isCube) {
  14031. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14032. }
  14033. var texture;
  14034. if (parsedTexture.mirrorPlane) {
  14035. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14036. texture._waitingRenderList = parsedTexture.renderList;
  14037. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14038. } else if (parsedTexture.isRenderTarget) {
  14039. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14040. texture._waitingRenderList = parsedTexture.renderList;
  14041. } else {
  14042. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14043. }
  14044. texture.name = parsedTexture.name;
  14045. texture.hasAlpha = parsedTexture.hasAlpha;
  14046. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14047. texture.level = parsedTexture.level;
  14048. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14049. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14050. texture.uOffset = parsedTexture.uOffset;
  14051. texture.vOffset = parsedTexture.vOffset;
  14052. texture.uScale = parsedTexture.uScale;
  14053. texture.vScale = parsedTexture.vScale;
  14054. texture.uAng = parsedTexture.uAng;
  14055. texture.vAng = parsedTexture.vAng;
  14056. texture.wAng = parsedTexture.wAng;
  14057. texture.wrapU = parsedTexture.wrapU;
  14058. texture.wrapV = parsedTexture.wrapV;
  14059. if (parsedTexture.animations) {
  14060. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14061. var parsedAnimation = parsedTexture.animations[animationIndex];
  14062. texture.animations.push(parseAnimation(parsedAnimation));
  14063. }
  14064. }
  14065. return texture;
  14066. };
  14067. var parseSkeleton = function (parsedSkeleton, scene) {
  14068. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14069. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14070. var parsedBone = parsedSkeleton.bones[index];
  14071. var parentBone = null;
  14072. if (parsedBone.parentBoneIndex > -1) {
  14073. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14074. }
  14075. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14076. if (parsedBone.animation) {
  14077. bone.animations.push(parseAnimation(parsedBone.animation));
  14078. }
  14079. }
  14080. return skeleton;
  14081. };
  14082. var parseFresnelParameters = function (parsedFresnelParameters) {
  14083. var fresnelParameters = new BABYLON.FresnelParameters();
  14084. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14085. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14086. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14087. fresnelParameters.bias = parsedFresnelParameters.bias;
  14088. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14089. return fresnelParameters;
  14090. };
  14091. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14092. var material;
  14093. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14094. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14095. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14096. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14097. material.specularPower = parsedMaterial.specularPower;
  14098. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14099. material.alpha = parsedMaterial.alpha;
  14100. material.id = parsedMaterial.id;
  14101. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14102. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14103. material.wireframe = parsedMaterial.wireframe;
  14104. if (parsedMaterial.diffuseTexture) {
  14105. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14106. }
  14107. if (parsedMaterial.diffuseFresnelParameters) {
  14108. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14109. }
  14110. if (parsedMaterial.ambientTexture) {
  14111. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14112. }
  14113. if (parsedMaterial.opacityTexture) {
  14114. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14115. }
  14116. if (parsedMaterial.opacityFresnelParameters) {
  14117. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14118. }
  14119. if (parsedMaterial.reflectionTexture) {
  14120. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14121. }
  14122. if (parsedMaterial.reflectionFresnelParameters) {
  14123. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14124. }
  14125. if (parsedMaterial.emissiveTexture) {
  14126. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14127. }
  14128. if (parsedMaterial.emissiveFresnelParameters) {
  14129. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14130. }
  14131. if (parsedMaterial.specularTexture) {
  14132. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14133. }
  14134. if (parsedMaterial.bumpTexture) {
  14135. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14136. }
  14137. return material;
  14138. };
  14139. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14140. for (var index = 0; index < parsedData.materials.length; index++) {
  14141. var parsedMaterial = parsedData.materials[index];
  14142. if (parsedMaterial.id === id) {
  14143. return parseMaterial(parsedMaterial, scene, rootUrl);
  14144. }
  14145. }
  14146. return null;
  14147. };
  14148. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14149. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14150. multiMaterial.id = parsedMultiMaterial.id;
  14151. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14152. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14153. var subMatId = parsedMultiMaterial.materials[matIndex];
  14154. if (subMatId) {
  14155. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14156. } else {
  14157. multiMaterial.subMaterials.push(null);
  14158. }
  14159. }
  14160. return multiMaterial;
  14161. };
  14162. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14163. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14164. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14165. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14166. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14167. var parsedFlare = parsedLensFlareSystem.flares[index];
  14168. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14169. }
  14170. return lensFlareSystem;
  14171. };
  14172. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14173. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14174. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14175. if (parsedParticleSystem.textureName) {
  14176. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14177. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14178. }
  14179. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14180. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14181. particleSystem.minSize = parsedParticleSystem.minSize;
  14182. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14183. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14184. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14185. particleSystem.emitter = emitter;
  14186. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14187. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14188. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14189. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14190. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14191. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14192. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14193. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14194. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14195. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14196. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14197. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14198. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14199. particleSystem.start();
  14200. return particleSystem;
  14201. };
  14202. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14203. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14204. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14205. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14206. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14207. shadowGenerator.getShadowMap().renderList.push(mesh);
  14208. }
  14209. if (parsedShadowGenerator.usePoissonSampling) {
  14210. shadowGenerator.usePoissonSampling = true;
  14211. } else {
  14212. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14213. }
  14214. return shadowGenerator;
  14215. };
  14216. var parseAnimation = function (parsedAnimation) {
  14217. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14218. var dataType = parsedAnimation.dataType;
  14219. var keys = [];
  14220. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14221. var key = parsedAnimation.keys[index];
  14222. var data;
  14223. switch (dataType) {
  14224. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14225. data = key.values[0];
  14226. break;
  14227. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14228. data = BABYLON.Quaternion.FromArray(key.values);
  14229. break;
  14230. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14231. data = BABYLON.Matrix.FromArray(key.values);
  14232. break;
  14233. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14234. default:
  14235. data = BABYLON.Vector3.FromArray(key.values);
  14236. break;
  14237. }
  14238. keys.push({
  14239. frame: key.frame,
  14240. value: data
  14241. });
  14242. }
  14243. animation.setKeys(keys);
  14244. return animation;
  14245. };
  14246. var parseLight = function (parsedLight, scene) {
  14247. var light;
  14248. switch (parsedLight.type) {
  14249. case 0:
  14250. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14251. break;
  14252. case 1:
  14253. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14254. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14255. break;
  14256. case 2:
  14257. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14258. break;
  14259. case 3:
  14260. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14261. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14262. break;
  14263. }
  14264. light.id = parsedLight.id;
  14265. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14266. if (parsedLight.intensity !== undefined) {
  14267. light.intensity = parsedLight.intensity;
  14268. }
  14269. if (parsedLight.range) {
  14270. light.range = parsedLight.range;
  14271. }
  14272. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14273. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14274. if (parsedLight.excludedMeshesIds) {
  14275. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14276. }
  14277. if (parsedLight.includedOnlyMeshesIds) {
  14278. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14279. }
  14280. if (parsedLight.animations) {
  14281. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14282. var parsedAnimation = parsedLight.animations[animationIndex];
  14283. light.animations.push(parseAnimation(parsedAnimation));
  14284. }
  14285. }
  14286. if (parsedLight.autoAnimate) {
  14287. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14288. }
  14289. };
  14290. var parseCamera = function (parsedCamera, scene) {
  14291. var camera;
  14292. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  14293. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  14294. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  14295. var alpha = parsedCamera.alpha;
  14296. var beta = parsedCamera.beta;
  14297. var radius = parsedCamera.radius;
  14298. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  14299. var eye_space = parsedCamera.eye_space;
  14300. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  14301. } else {
  14302. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  14303. }
  14304. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  14305. var eye_space = parsedCamera.eye_space;
  14306. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  14307. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  14308. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  14309. } else if (parsedCamera.type === "FollowCamera") {
  14310. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  14311. camera.heightOffset = parsedCamera.heightOffset;
  14312. camera.radius = parsedCamera.radius;
  14313. camera.rotationOffset = parsedCamera.rotationOffset;
  14314. if (lockedTargetMesh)
  14315. camera.target = lockedTargetMesh;
  14316. } else if (parsedCamera.type === "GamepadCamera") {
  14317. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  14318. } else if (parsedCamera.type === "OculusCamera") {
  14319. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  14320. } else if (parsedCamera.type === "TouchCamera") {
  14321. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  14322. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  14323. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  14324. } else if (parsedCamera.type === "WebVRCamera") {
  14325. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  14326. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  14327. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  14328. } else {
  14329. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  14330. }
  14331. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  14332. camera.lockedTarget = lockedTargetMesh;
  14333. }
  14334. camera.id = parsedCamera.id;
  14335. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14336. if (parsedCamera.parentId) {
  14337. camera._waitingParentId = parsedCamera.parentId;
  14338. }
  14339. if (parsedCamera.target) {
  14340. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14341. } else {
  14342. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14343. }
  14344. camera.fov = parsedCamera.fov;
  14345. camera.minZ = parsedCamera.minZ;
  14346. camera.maxZ = parsedCamera.maxZ;
  14347. camera.speed = parsedCamera.speed;
  14348. camera.inertia = parsedCamera.inertia;
  14349. camera.checkCollisions = parsedCamera.checkCollisions;
  14350. camera.applyGravity = parsedCamera.applyGravity;
  14351. if (parsedCamera.ellipsoid) {
  14352. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14353. }
  14354. if (parsedCamera.animations) {
  14355. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14356. var parsedAnimation = parsedCamera.animations[animationIndex];
  14357. camera.animations.push(parseAnimation(parsedAnimation));
  14358. }
  14359. }
  14360. if (parsedCamera.autoAnimate) {
  14361. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14362. }
  14363. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14364. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14365. } else {
  14366. camera.layerMask = 0xFFFFFFFF;
  14367. }
  14368. return camera;
  14369. };
  14370. var parseGeometry = function (parsedGeometry, scene) {
  14371. var id = parsedGeometry.id;
  14372. return scene.getGeometryByID(id);
  14373. };
  14374. var parseBox = function (parsedBox, scene) {
  14375. if (parseGeometry(parsedBox, scene)) {
  14376. return null;
  14377. }
  14378. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14379. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14380. scene.pushGeometry(box, true);
  14381. return box;
  14382. };
  14383. var parseSphere = function (parsedSphere, scene) {
  14384. if (parseGeometry(parsedSphere, scene)) {
  14385. return null;
  14386. }
  14387. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14388. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14389. scene.pushGeometry(sphere, true);
  14390. return sphere;
  14391. };
  14392. var parseCylinder = function (parsedCylinder, scene) {
  14393. if (parseGeometry(parsedCylinder, scene)) {
  14394. return null;
  14395. }
  14396. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14397. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14398. scene.pushGeometry(cylinder, true);
  14399. return cylinder;
  14400. };
  14401. var parseTorus = function (parsedTorus, scene) {
  14402. if (parseGeometry(parsedTorus, scene)) {
  14403. return null;
  14404. }
  14405. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14406. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14407. scene.pushGeometry(torus, true);
  14408. return torus;
  14409. };
  14410. var parseGround = function (parsedGround, scene) {
  14411. if (parseGeometry(parsedGround, scene)) {
  14412. return null;
  14413. }
  14414. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14415. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14416. scene.pushGeometry(ground, true);
  14417. return ground;
  14418. };
  14419. var parsePlane = function (parsedPlane, scene) {
  14420. if (parseGeometry(parsedPlane, scene)) {
  14421. return null;
  14422. }
  14423. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14424. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14425. scene.pushGeometry(plane, true);
  14426. return plane;
  14427. };
  14428. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14429. if (parseGeometry(parsedTorusKnot, scene)) {
  14430. return null;
  14431. }
  14432. 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);
  14433. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14434. scene.pushGeometry(torusKnot, true);
  14435. return torusKnot;
  14436. };
  14437. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14438. if (parseGeometry(parsedVertexData, scene)) {
  14439. return null;
  14440. }
  14441. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14442. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14443. if (parsedVertexData.delayLoadingFile) {
  14444. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14445. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14446. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14447. geometry._delayInfo = [];
  14448. if (parsedVertexData.hasUVs) {
  14449. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14450. }
  14451. if (parsedVertexData.hasUVs2) {
  14452. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14453. }
  14454. if (parsedVertexData.hasColors) {
  14455. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14456. }
  14457. if (parsedVertexData.hasMatricesIndices) {
  14458. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14459. }
  14460. if (parsedVertexData.hasMatricesWeights) {
  14461. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14462. }
  14463. geometry._delayLoadingFunction = importVertexData;
  14464. } else {
  14465. importVertexData(parsedVertexData, geometry);
  14466. }
  14467. scene.pushGeometry(geometry, true);
  14468. return geometry;
  14469. };
  14470. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14471. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14472. mesh.id = parsedMesh.id;
  14473. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14474. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14475. if (parsedMesh.rotationQuaternion) {
  14476. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14477. } else if (parsedMesh.rotation) {
  14478. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14479. }
  14480. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14481. if (parsedMesh.localMatrix) {
  14482. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14483. } else if (parsedMesh.pivotMatrix) {
  14484. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14485. }
  14486. mesh.setEnabled(parsedMesh.isEnabled);
  14487. mesh.isVisible = parsedMesh.isVisible;
  14488. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14489. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14490. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14491. if (parsedMesh.pickable !== undefined) {
  14492. mesh.isPickable = parsedMesh.pickable;
  14493. }
  14494. mesh.receiveShadows = parsedMesh.receiveShadows;
  14495. mesh.billboardMode = parsedMesh.billboardMode;
  14496. if (parsedMesh.visibility !== undefined) {
  14497. mesh.visibility = parsedMesh.visibility;
  14498. }
  14499. mesh.checkCollisions = parsedMesh.checkCollisions;
  14500. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14501. if (parsedMesh.parentId) {
  14502. mesh._waitingParentId = parsedMesh.parentId;
  14503. }
  14504. if (parsedMesh.delayLoadingFile) {
  14505. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14506. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14507. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14508. if (parsedMesh._binaryInfo) {
  14509. mesh._binaryInfo = parsedMesh._binaryInfo;
  14510. }
  14511. mesh._delayInfo = [];
  14512. if (parsedMesh.hasUVs) {
  14513. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14514. }
  14515. if (parsedMesh.hasUVs2) {
  14516. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14517. }
  14518. if (parsedMesh.hasColors) {
  14519. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14520. }
  14521. if (parsedMesh.hasMatricesIndices) {
  14522. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14523. }
  14524. if (parsedMesh.hasMatricesWeights) {
  14525. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14526. }
  14527. mesh._delayLoadingFunction = importGeometry;
  14528. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14529. mesh._checkDelayState();
  14530. }
  14531. } else {
  14532. importGeometry(parsedMesh, mesh);
  14533. }
  14534. if (parsedMesh.materialId) {
  14535. mesh.setMaterialByID(parsedMesh.materialId);
  14536. } else {
  14537. mesh.material = null;
  14538. }
  14539. if (parsedMesh.skeletonId > -1) {
  14540. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14541. }
  14542. if (parsedMesh.physicsImpostor) {
  14543. if (!scene.isPhysicsEnabled()) {
  14544. scene.enablePhysics();
  14545. }
  14546. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14547. }
  14548. if (parsedMesh.animations) {
  14549. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14550. var parsedAnimation = parsedMesh.animations[animationIndex];
  14551. mesh.animations.push(parseAnimation(parsedAnimation));
  14552. }
  14553. }
  14554. if (parsedMesh.autoAnimate) {
  14555. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14556. }
  14557. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14558. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14559. } else {
  14560. mesh.layerMask = 0xFFFFFFFF;
  14561. }
  14562. if (parsedMesh.instances) {
  14563. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14564. var parsedInstance = parsedMesh.instances[index];
  14565. var instance = mesh.createInstance(parsedInstance.name);
  14566. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14567. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14568. if (parsedInstance.rotationQuaternion) {
  14569. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14570. } else if (parsedInstance.rotation) {
  14571. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14572. }
  14573. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14574. instance.checkCollisions = mesh.checkCollisions;
  14575. if (parsedMesh.animations) {
  14576. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14577. parsedAnimation = parsedMesh.animations[animationIndex];
  14578. instance.animations.push(parseAnimation(parsedAnimation));
  14579. }
  14580. }
  14581. }
  14582. }
  14583. return mesh;
  14584. };
  14585. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14586. names = (names instanceof Array) ? names : [names];
  14587. for (var i in names) {
  14588. if (mesh.name === names[i]) {
  14589. hierarchyIds.push(mesh.id);
  14590. return true;
  14591. }
  14592. }
  14593. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14594. hierarchyIds.push(mesh.id);
  14595. return true;
  14596. }
  14597. return false;
  14598. };
  14599. var importVertexData = function (parsedVertexData, geometry) {
  14600. var vertexData = new BABYLON.VertexData();
  14601. var positions = parsedVertexData.positions;
  14602. if (positions) {
  14603. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14604. }
  14605. var normals = parsedVertexData.normals;
  14606. if (normals) {
  14607. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14608. }
  14609. var uvs = parsedVertexData.uvs;
  14610. if (uvs) {
  14611. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14612. }
  14613. var uv2s = parsedVertexData.uv2s;
  14614. if (uv2s) {
  14615. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14616. }
  14617. var colors = parsedVertexData.colors;
  14618. if (colors) {
  14619. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14620. }
  14621. var matricesIndices = parsedVertexData.matricesIndices;
  14622. if (matricesIndices) {
  14623. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14624. }
  14625. var matricesWeights = parsedVertexData.matricesWeights;
  14626. if (matricesWeights) {
  14627. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14628. }
  14629. var indices = parsedVertexData.indices;
  14630. if (indices) {
  14631. vertexData.indices = indices;
  14632. }
  14633. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14634. };
  14635. var importGeometry = function (parsedGeometry, mesh) {
  14636. var scene = mesh.getScene();
  14637. var geometryId = parsedGeometry.geometryId;
  14638. if (geometryId) {
  14639. var geometry = scene.getGeometryByID(geometryId);
  14640. if (geometry) {
  14641. geometry.applyToMesh(mesh);
  14642. }
  14643. } else if (parsedGeometry instanceof ArrayBuffer) {
  14644. var binaryInfo = mesh._binaryInfo;
  14645. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  14646. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  14647. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  14648. }
  14649. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  14650. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  14651. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  14652. }
  14653. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  14654. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  14655. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  14656. }
  14657. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  14658. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  14659. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  14660. }
  14661. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  14662. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  14663. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  14664. }
  14665. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  14666. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  14667. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  14668. }
  14669. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  14670. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  14671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  14672. }
  14673. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  14674. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  14675. mesh.setIndices(indicesData);
  14676. }
  14677. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  14678. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  14679. mesh.subMeshes = [];
  14680. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  14681. var materialIndex = subMeshesData[(i * 5) + 0];
  14682. var verticesStart = subMeshesData[(i * 5) + 1];
  14683. var verticesCount = subMeshesData[(i * 5) + 2];
  14684. var indexStart = subMeshesData[(i * 5) + 3];
  14685. var indexCount = subMeshesData[(i * 5) + 4];
  14686. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  14687. }
  14688. }
  14689. return;
  14690. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14691. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14692. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14693. if (parsedGeometry.uvs) {
  14694. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14695. }
  14696. if (parsedGeometry.uvs2) {
  14697. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14698. }
  14699. if (parsedGeometry.colors) {
  14700. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14701. }
  14702. if (parsedGeometry.matricesIndices) {
  14703. if (!parsedGeometry.matricesIndices._isExpanded) {
  14704. var floatIndices = [];
  14705. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14706. var matricesIndex = parsedGeometry.matricesIndices[i];
  14707. floatIndices.push(matricesIndex & 0x000000FF);
  14708. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14709. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14710. floatIndices.push(matricesIndex >> 24);
  14711. }
  14712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14713. } else {
  14714. delete parsedGeometry.matricesIndices._isExpanded;
  14715. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14716. }
  14717. }
  14718. if (parsedGeometry.matricesWeights) {
  14719. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14720. }
  14721. mesh.setIndices(parsedGeometry.indices);
  14722. }
  14723. if (parsedGeometry.subMeshes) {
  14724. mesh.subMeshes = [];
  14725. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14726. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14727. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14728. }
  14729. }
  14730. if (mesh._shouldGenerateFlatShading) {
  14731. mesh.convertToFlatShadedMesh();
  14732. delete mesh._shouldGenerateFlatShading;
  14733. }
  14734. mesh.computeWorldMatrix(true);
  14735. if (scene._selectionOctree) {
  14736. scene._selectionOctree.addMesh(mesh);
  14737. }
  14738. };
  14739. BABYLON.SceneLoader.RegisterPlugin({
  14740. extensions: ".babylon",
  14741. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14742. var parsedData = JSON.parse(data);
  14743. var loadedSkeletonsIds = [];
  14744. var loadedMaterialsIds = [];
  14745. var hierarchyIds = [];
  14746. for (var index = 0; index < parsedData.meshes.length; index++) {
  14747. var parsedMesh = parsedData.meshes[index];
  14748. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14749. if (meshesNames instanceof Array) {
  14750. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14751. }
  14752. if (parsedMesh.materialId) {
  14753. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14754. if (!materialFound) {
  14755. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14756. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14757. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14758. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14759. var subMatId = parsedMultiMaterial.materials[matIndex];
  14760. loadedMaterialsIds.push(subMatId);
  14761. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14762. }
  14763. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14764. parseMultiMaterial(parsedMultiMaterial, scene);
  14765. materialFound = true;
  14766. break;
  14767. }
  14768. }
  14769. }
  14770. if (!materialFound) {
  14771. loadedMaterialsIds.push(parsedMesh.materialId);
  14772. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14773. }
  14774. }
  14775. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14776. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14777. if (!skeletonAlreadyLoaded) {
  14778. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14779. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14780. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14781. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14782. loadedSkeletonsIds.push(parsedSkeleton.id);
  14783. }
  14784. }
  14785. }
  14786. }
  14787. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14788. meshes.push(mesh);
  14789. }
  14790. }
  14791. for (index = 0; index < scene.meshes.length; index++) {
  14792. var currentMesh = scene.meshes[index];
  14793. if (currentMesh._waitingParentId) {
  14794. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  14795. currentMesh._waitingParentId = undefined;
  14796. }
  14797. }
  14798. if (parsedData.particleSystems) {
  14799. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14800. var parsedParticleSystem = parsedData.particleSystems[index];
  14801. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14802. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14803. }
  14804. }
  14805. }
  14806. return true;
  14807. },
  14808. load: function (scene, data, rootUrl) {
  14809. var parsedData = JSON.parse(data);
  14810. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14811. scene.autoClear = parsedData.autoClear;
  14812. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14813. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14814. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14815. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14816. scene.fogMode = parsedData.fogMode;
  14817. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14818. scene.fogStart = parsedData.fogStart;
  14819. scene.fogEnd = parsedData.fogEnd;
  14820. scene.fogDensity = parsedData.fogDensity;
  14821. }
  14822. for (var index = 0; index < parsedData.lights.length; index++) {
  14823. var parsedLight = parsedData.lights[index];
  14824. parseLight(parsedLight, scene);
  14825. }
  14826. if (parsedData.materials) {
  14827. for (index = 0; index < parsedData.materials.length; index++) {
  14828. var parsedMaterial = parsedData.materials[index];
  14829. parseMaterial(parsedMaterial, scene, rootUrl);
  14830. }
  14831. }
  14832. if (parsedData.multiMaterials) {
  14833. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14834. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14835. parseMultiMaterial(parsedMultiMaterial, scene);
  14836. }
  14837. }
  14838. if (parsedData.skeletons) {
  14839. for (index = 0; index < parsedData.skeletons.length; index++) {
  14840. var parsedSkeleton = parsedData.skeletons[index];
  14841. parseSkeleton(parsedSkeleton, scene);
  14842. }
  14843. }
  14844. var geometries = parsedData.geometries;
  14845. if (geometries) {
  14846. var boxes = geometries.boxes;
  14847. if (boxes) {
  14848. for (index = 0; index < boxes.length; index++) {
  14849. var parsedBox = boxes[index];
  14850. parseBox(parsedBox, scene);
  14851. }
  14852. }
  14853. var spheres = geometries.spheres;
  14854. if (spheres) {
  14855. for (index = 0; index < spheres.length; index++) {
  14856. var parsedSphere = spheres[index];
  14857. parseSphere(parsedSphere, scene);
  14858. }
  14859. }
  14860. var cylinders = geometries.cylinders;
  14861. if (cylinders) {
  14862. for (index = 0; index < cylinders.length; index++) {
  14863. var parsedCylinder = cylinders[index];
  14864. parseCylinder(parsedCylinder, scene);
  14865. }
  14866. }
  14867. var toruses = geometries.toruses;
  14868. if (toruses) {
  14869. for (index = 0; index < toruses.length; index++) {
  14870. var parsedTorus = toruses[index];
  14871. parseTorus(parsedTorus, scene);
  14872. }
  14873. }
  14874. var grounds = geometries.grounds;
  14875. if (grounds) {
  14876. for (index = 0; index < grounds.length; index++) {
  14877. var parsedGround = grounds[index];
  14878. parseGround(parsedGround, scene);
  14879. }
  14880. }
  14881. var planes = geometries.planes;
  14882. if (planes) {
  14883. for (index = 0; index < planes.length; index++) {
  14884. var parsedPlane = planes[index];
  14885. parsePlane(parsedPlane, scene);
  14886. }
  14887. }
  14888. var torusKnots = geometries.torusKnots;
  14889. if (torusKnots) {
  14890. for (index = 0; index < torusKnots.length; index++) {
  14891. var parsedTorusKnot = torusKnots[index];
  14892. parseTorusKnot(parsedTorusKnot, scene);
  14893. }
  14894. }
  14895. var vertexData = geometries.vertexData;
  14896. if (vertexData) {
  14897. for (index = 0; index < vertexData.length; index++) {
  14898. var parsedVertexData = vertexData[index];
  14899. parseVertexData(parsedVertexData, scene, rootUrl);
  14900. }
  14901. }
  14902. }
  14903. for (index = 0; index < parsedData.meshes.length; index++) {
  14904. var parsedMesh = parsedData.meshes[index];
  14905. parseMesh(parsedMesh, scene, rootUrl);
  14906. }
  14907. for (index = 0; index < parsedData.cameras.length; index++) {
  14908. var parsedCamera = parsedData.cameras[index];
  14909. parseCamera(parsedCamera, scene);
  14910. }
  14911. if (parsedData.activeCameraID) {
  14912. scene.setActiveCameraByID(parsedData.activeCameraID);
  14913. }
  14914. for (index = 0; index < scene.cameras.length; index++) {
  14915. var camera = scene.cameras[index];
  14916. if (camera._waitingParentId) {
  14917. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14918. camera._waitingParentId = undefined;
  14919. }
  14920. }
  14921. for (index = 0; index < scene.meshes.length; index++) {
  14922. var mesh = scene.meshes[index];
  14923. if (mesh._waitingParentId) {
  14924. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  14925. mesh._waitingParentId = undefined;
  14926. }
  14927. }
  14928. if (parsedData.particleSystems) {
  14929. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14930. var parsedParticleSystem = parsedData.particleSystems[index];
  14931. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14932. }
  14933. }
  14934. if (parsedData.lensFlareSystems) {
  14935. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14936. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14937. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14938. }
  14939. }
  14940. if (parsedData.shadowGenerators) {
  14941. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14942. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14943. parseShadowGenerator(parsedShadowGenerator, scene);
  14944. }
  14945. }
  14946. return true;
  14947. }
  14948. });
  14949. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14950. var Internals = BABYLON.Internals;
  14951. })(BABYLON || (BABYLON = {}));
  14952. var BABYLON;
  14953. (function (BABYLON) {
  14954. var currentCSGMeshId = 0;
  14955. var Vertex = (function () {
  14956. function Vertex(pos, normal, uv) {
  14957. this.pos = pos;
  14958. this.normal = normal;
  14959. this.uv = uv;
  14960. }
  14961. Vertex.prototype.clone = function () {
  14962. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14963. };
  14964. Vertex.prototype.flip = function () {
  14965. this.normal = this.normal.scale(-1);
  14966. };
  14967. Vertex.prototype.interpolate = function (other, t) {
  14968. 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));
  14969. };
  14970. return Vertex;
  14971. })();
  14972. var Plane = (function () {
  14973. function Plane(normal, w) {
  14974. this.normal = normal;
  14975. this.w = w;
  14976. }
  14977. Plane.FromPoints = function (a, b, c) {
  14978. var v0 = c.subtract(a);
  14979. var v1 = b.subtract(a);
  14980. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14981. return null;
  14982. }
  14983. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14984. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14985. };
  14986. Plane.prototype.clone = function () {
  14987. return new Plane(this.normal.clone(), this.w);
  14988. };
  14989. Plane.prototype.flip = function () {
  14990. this.normal.scaleInPlace(-1);
  14991. this.w = -this.w;
  14992. };
  14993. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14994. var COPLANAR = 0;
  14995. var FRONT = 1;
  14996. var BACK = 2;
  14997. var SPANNING = 3;
  14998. var polygonType = 0;
  14999. var types = [];
  15000. for (var i = 0; i < polygon.vertices.length; i++) {
  15001. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15002. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15003. polygonType |= type;
  15004. types.push(type);
  15005. }
  15006. switch (polygonType) {
  15007. case COPLANAR:
  15008. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15009. break;
  15010. case FRONT:
  15011. front.push(polygon);
  15012. break;
  15013. case BACK:
  15014. back.push(polygon);
  15015. break;
  15016. case SPANNING:
  15017. var f = [], b = [];
  15018. for (i = 0; i < polygon.vertices.length; i++) {
  15019. var j = (i + 1) % polygon.vertices.length;
  15020. var ti = types[i], tj = types[j];
  15021. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15022. if (ti != BACK)
  15023. f.push(vi);
  15024. if (ti != FRONT)
  15025. b.push(ti != BACK ? vi.clone() : vi);
  15026. if ((ti | tj) == SPANNING) {
  15027. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15028. var v = vi.interpolate(vj, t);
  15029. f.push(v);
  15030. b.push(v.clone());
  15031. }
  15032. }
  15033. if (f.length >= 3) {
  15034. var poly = new Polygon(f, polygon.shared);
  15035. if (poly.plane)
  15036. front.push(poly);
  15037. }
  15038. if (b.length >= 3) {
  15039. poly = new Polygon(b, polygon.shared);
  15040. if (poly.plane)
  15041. back.push(poly);
  15042. }
  15043. break;
  15044. }
  15045. };
  15046. Plane.EPSILON = 1e-5;
  15047. return Plane;
  15048. })();
  15049. var Polygon = (function () {
  15050. function Polygon(vertices, shared) {
  15051. this.vertices = vertices;
  15052. this.shared = shared;
  15053. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15054. }
  15055. Polygon.prototype.clone = function () {
  15056. var vertices = this.vertices.map(function (v) {
  15057. return v.clone();
  15058. });
  15059. return new Polygon(vertices, this.shared);
  15060. };
  15061. Polygon.prototype.flip = function () {
  15062. this.vertices.reverse().map(function (v) {
  15063. v.flip();
  15064. });
  15065. this.plane.flip();
  15066. };
  15067. return Polygon;
  15068. })();
  15069. var Node = (function () {
  15070. function Node(polygons) {
  15071. this.plane = null;
  15072. this.front = null;
  15073. this.back = null;
  15074. this.polygons = [];
  15075. if (polygons) {
  15076. this.build(polygons);
  15077. }
  15078. }
  15079. Node.prototype.clone = function () {
  15080. var node = new Node();
  15081. node.plane = this.plane && this.plane.clone();
  15082. node.front = this.front && this.front.clone();
  15083. node.back = this.back && this.back.clone();
  15084. node.polygons = this.polygons.map(function (p) {
  15085. return p.clone();
  15086. });
  15087. return node;
  15088. };
  15089. Node.prototype.invert = function () {
  15090. for (var i = 0; i < this.polygons.length; i++) {
  15091. this.polygons[i].flip();
  15092. }
  15093. if (this.plane) {
  15094. this.plane.flip();
  15095. }
  15096. if (this.front) {
  15097. this.front.invert();
  15098. }
  15099. if (this.back) {
  15100. this.back.invert();
  15101. }
  15102. var temp = this.front;
  15103. this.front = this.back;
  15104. this.back = temp;
  15105. };
  15106. Node.prototype.clipPolygons = function (polygons) {
  15107. if (!this.plane)
  15108. return polygons.slice();
  15109. var front = [], back = [];
  15110. for (var i = 0; i < polygons.length; i++) {
  15111. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15112. }
  15113. if (this.front) {
  15114. front = this.front.clipPolygons(front);
  15115. }
  15116. if (this.back) {
  15117. back = this.back.clipPolygons(back);
  15118. } else {
  15119. back = [];
  15120. }
  15121. return front.concat(back);
  15122. };
  15123. Node.prototype.clipTo = function (bsp) {
  15124. this.polygons = bsp.clipPolygons(this.polygons);
  15125. if (this.front)
  15126. this.front.clipTo(bsp);
  15127. if (this.back)
  15128. this.back.clipTo(bsp);
  15129. };
  15130. Node.prototype.allPolygons = function () {
  15131. var polygons = this.polygons.slice();
  15132. if (this.front)
  15133. polygons = polygons.concat(this.front.allPolygons());
  15134. if (this.back)
  15135. polygons = polygons.concat(this.back.allPolygons());
  15136. return polygons;
  15137. };
  15138. Node.prototype.build = function (polygons) {
  15139. if (!polygons.length)
  15140. return;
  15141. if (!this.plane)
  15142. this.plane = polygons[0].plane.clone();
  15143. var front = [], back = [];
  15144. for (var i = 0; i < polygons.length; i++) {
  15145. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15146. }
  15147. if (front.length) {
  15148. if (!this.front)
  15149. this.front = new Node();
  15150. this.front.build(front);
  15151. }
  15152. if (back.length) {
  15153. if (!this.back)
  15154. this.back = new Node();
  15155. this.back.build(back);
  15156. }
  15157. };
  15158. return Node;
  15159. })();
  15160. var CSG = (function () {
  15161. function CSG() {
  15162. this.polygons = new Array();
  15163. }
  15164. CSG.FromMesh = function (mesh) {
  15165. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15166. if (mesh instanceof BABYLON.Mesh) {
  15167. mesh.computeWorldMatrix(true);
  15168. var matrix = mesh.getWorldMatrix();
  15169. var meshPosition = mesh.position.clone();
  15170. var meshRotation = mesh.rotation.clone();
  15171. var meshScaling = mesh.scaling.clone();
  15172. } else {
  15173. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15174. }
  15175. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15176. var subMeshes = mesh.subMeshes;
  15177. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15178. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15179. vertices = [];
  15180. for (var j = 0; j < 3; j++) {
  15181. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15182. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15183. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15184. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15185. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15186. vertex = new Vertex(position, normal, uv);
  15187. vertices.push(vertex);
  15188. }
  15189. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15190. if (polygon.plane)
  15191. polygons.push(polygon);
  15192. }
  15193. }
  15194. var csg = CSG.FromPolygons(polygons);
  15195. csg.matrix = matrix;
  15196. csg.position = meshPosition;
  15197. csg.rotation = meshRotation;
  15198. csg.scaling = meshScaling;
  15199. currentCSGMeshId++;
  15200. return csg;
  15201. };
  15202. CSG.FromPolygons = function (polygons) {
  15203. var csg = new BABYLON.CSG();
  15204. csg.polygons = polygons;
  15205. return csg;
  15206. };
  15207. CSG.prototype.clone = function () {
  15208. var csg = new BABYLON.CSG();
  15209. csg.polygons = this.polygons.map(function (p) {
  15210. return p.clone();
  15211. });
  15212. csg.copyTransformAttributes(this);
  15213. return csg;
  15214. };
  15215. CSG.prototype.toPolygons = function () {
  15216. return this.polygons;
  15217. };
  15218. CSG.prototype.union = function (csg) {
  15219. var a = new Node(this.clone().polygons);
  15220. var b = new Node(csg.clone().polygons);
  15221. a.clipTo(b);
  15222. b.clipTo(a);
  15223. b.invert();
  15224. b.clipTo(a);
  15225. b.invert();
  15226. a.build(b.allPolygons());
  15227. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15228. };
  15229. CSG.prototype.unionInPlace = function (csg) {
  15230. var a = new Node(this.polygons);
  15231. var b = new Node(csg.polygons);
  15232. a.clipTo(b);
  15233. b.clipTo(a);
  15234. b.invert();
  15235. b.clipTo(a);
  15236. b.invert();
  15237. a.build(b.allPolygons());
  15238. this.polygons = a.allPolygons();
  15239. };
  15240. CSG.prototype.subtract = function (csg) {
  15241. var a = new Node(this.clone().polygons);
  15242. var b = new Node(csg.clone().polygons);
  15243. a.invert();
  15244. a.clipTo(b);
  15245. b.clipTo(a);
  15246. b.invert();
  15247. b.clipTo(a);
  15248. b.invert();
  15249. a.build(b.allPolygons());
  15250. a.invert();
  15251. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15252. };
  15253. CSG.prototype.subtractInPlace = function (csg) {
  15254. var a = new Node(this.polygons);
  15255. var b = new Node(csg.polygons);
  15256. a.invert();
  15257. a.clipTo(b);
  15258. b.clipTo(a);
  15259. b.invert();
  15260. b.clipTo(a);
  15261. b.invert();
  15262. a.build(b.allPolygons());
  15263. a.invert();
  15264. this.polygons = a.allPolygons();
  15265. };
  15266. CSG.prototype.intersect = function (csg) {
  15267. var a = new Node(this.clone().polygons);
  15268. var b = new Node(csg.clone().polygons);
  15269. a.invert();
  15270. b.clipTo(a);
  15271. b.invert();
  15272. a.clipTo(b);
  15273. b.clipTo(a);
  15274. a.build(b.allPolygons());
  15275. a.invert();
  15276. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15277. };
  15278. CSG.prototype.intersectInPlace = function (csg) {
  15279. var a = new Node(this.polygons);
  15280. var b = new Node(csg.polygons);
  15281. a.invert();
  15282. b.clipTo(a);
  15283. b.invert();
  15284. a.clipTo(b);
  15285. b.clipTo(a);
  15286. a.build(b.allPolygons());
  15287. a.invert();
  15288. this.polygons = a.allPolygons();
  15289. };
  15290. CSG.prototype.inverse = function () {
  15291. var csg = this.clone();
  15292. csg.inverseInPlace();
  15293. return csg;
  15294. };
  15295. CSG.prototype.inverseInPlace = function () {
  15296. this.polygons.map(function (p) {
  15297. p.flip();
  15298. });
  15299. };
  15300. CSG.prototype.copyTransformAttributes = function (csg) {
  15301. this.matrix = csg.matrix;
  15302. this.position = csg.position;
  15303. this.rotation = csg.rotation;
  15304. this.scaling = csg.scaling;
  15305. return this;
  15306. };
  15307. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15308. var matrix = this.matrix.clone();
  15309. matrix.invert();
  15310. 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;
  15311. if (keepSubMeshes) {
  15312. polygons.sort(function (a, b) {
  15313. if (a.shared.meshId === b.shared.meshId) {
  15314. return a.shared.subMeshId - b.shared.subMeshId;
  15315. } else {
  15316. return a.shared.meshId - b.shared.meshId;
  15317. }
  15318. });
  15319. }
  15320. for (var i = 0, il = polygons.length; i < il; i++) {
  15321. polygon = polygons[i];
  15322. if (!subMesh_dict[polygon.shared.meshId]) {
  15323. subMesh_dict[polygon.shared.meshId] = {};
  15324. }
  15325. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15326. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15327. indexStart: +Infinity,
  15328. indexEnd: -Infinity,
  15329. materialIndex: polygon.shared.materialIndex
  15330. };
  15331. }
  15332. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15333. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15334. polygonIndices[0] = 0;
  15335. polygonIndices[1] = j - 1;
  15336. polygonIndices[2] = j;
  15337. for (var k = 0; k < 3; k++) {
  15338. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15339. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15340. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15341. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15342. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15343. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15344. 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)) {
  15345. vertices.push(vertex.x, vertex.y, vertex.z);
  15346. uvs.push(uv.x, uv.y);
  15347. normals.push(normal.x, normal.y, normal.z);
  15348. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15349. }
  15350. indices.push(vertex_idx);
  15351. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15352. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15353. currentIndex++;
  15354. }
  15355. }
  15356. }
  15357. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15358. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15359. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15360. mesh.setIndices(indices);
  15361. if (keepSubMeshes) {
  15362. var materialIndexOffset = 0, materialMaxIndex;
  15363. mesh.subMeshes.length = 0;
  15364. for (var m in subMesh_dict) {
  15365. materialMaxIndex = -1;
  15366. for (var sm in subMesh_dict[m]) {
  15367. subMesh_obj = subMesh_dict[m][sm];
  15368. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15369. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15370. }
  15371. materialIndexOffset += ++materialMaxIndex;
  15372. }
  15373. }
  15374. return mesh;
  15375. };
  15376. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15377. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15378. mesh.material = material;
  15379. mesh.position.copyFrom(this.position);
  15380. mesh.rotation.copyFrom(this.rotation);
  15381. mesh.scaling.copyFrom(this.scaling);
  15382. mesh.computeWorldMatrix(true);
  15383. return mesh;
  15384. };
  15385. return CSG;
  15386. })();
  15387. BABYLON.CSG = CSG;
  15388. })(BABYLON || (BABYLON = {}));
  15389. var __extends = this.__extends || function (d, b) {
  15390. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15391. function __() { this.constructor = d; }
  15392. __.prototype = b.prototype;
  15393. d.prototype = new __();
  15394. };
  15395. var BABYLON;
  15396. (function (BABYLON) {
  15397. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15398. __extends(OculusDistortionCorrectionPostProcess, _super);
  15399. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15400. var _this = this;
  15401. _super.call(this, name, "oculusDistortionCorrection", [
  15402. 'LensCenter',
  15403. 'Scale',
  15404. 'ScaleIn',
  15405. 'HmdWarpParam'
  15406. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15407. this._isRightEye = isRightEye;
  15408. this._distortionFactors = cameraSettings.DistortionK;
  15409. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15410. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15411. this.onSizeChanged = function () {
  15412. _this.aspectRatio = _this.width * .5 / _this.height;
  15413. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15414. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15415. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15416. };
  15417. this.onApply = function (effect) {
  15418. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15419. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15420. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15421. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15422. };
  15423. }
  15424. return OculusDistortionCorrectionPostProcess;
  15425. })(BABYLON.PostProcess);
  15426. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15427. })(BABYLON || (BABYLON = {}));
  15428. var BABYLON;
  15429. (function (BABYLON) {
  15430. (function (JoystickAxis) {
  15431. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15432. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15433. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15434. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15435. var JoystickAxis = BABYLON.JoystickAxis;
  15436. var VirtualJoystick = (function () {
  15437. function VirtualJoystick(leftJoystick) {
  15438. var _this = this;
  15439. if (leftJoystick) {
  15440. this._leftJoystick = true;
  15441. } else {
  15442. this._leftJoystick = false;
  15443. }
  15444. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15445. VirtualJoystick._globalJoystickIndex++;
  15446. this._axisTargetedByLeftAndRight = 0 /* X */;
  15447. this._axisTargetedByUpAndDown = 1 /* Y */;
  15448. this.reverseLeftRight = false;
  15449. this.reverseUpDown = false;
  15450. this._touches = new BABYLON.VirtualJoystick.Collection();
  15451. this.deltaPosition = BABYLON.Vector3.Zero();
  15452. this._joystickSensibility = 25;
  15453. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15454. this._rotationSpeed = 25;
  15455. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15456. this._rotateOnAxisRelativeToMesh = false;
  15457. if (!VirtualJoystick.vjCanvas) {
  15458. window.addEventListener("resize", function () {
  15459. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15460. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15461. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15462. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15463. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15464. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15465. }, false);
  15466. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15467. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15468. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15469. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15470. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15471. VirtualJoystick.vjCanvas.style.width = "100%";
  15472. VirtualJoystick.vjCanvas.style.height = "100%";
  15473. VirtualJoystick.vjCanvas.style.position = "absolute";
  15474. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15475. VirtualJoystick.vjCanvas.style.top = "0px";
  15476. VirtualJoystick.vjCanvas.style.left = "0px";
  15477. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15478. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15479. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15480. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15481. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15482. document.body.appendChild(VirtualJoystick.vjCanvas);
  15483. }
  15484. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15485. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15486. this.pressed = false;
  15487. this._joystickColor = "cyan";
  15488. this._joystickPointerID = -1;
  15489. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15490. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15491. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15492. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15493. _this._onPointerDown(evt);
  15494. }, false);
  15495. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15496. _this._onPointerMove(evt);
  15497. }, false);
  15498. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15499. _this._onPointerUp(evt);
  15500. }, false);
  15501. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15502. _this._onPointerUp(evt);
  15503. }, false);
  15504. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15505. evt.preventDefault();
  15506. }, false);
  15507. requestAnimationFrame(function () {
  15508. _this._drawVirtualJoystick();
  15509. });
  15510. }
  15511. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15512. this._joystickSensibility = newJoystickSensibility;
  15513. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15514. };
  15515. VirtualJoystick.prototype._onPointerDown = function (e) {
  15516. var positionOnScreenCondition;
  15517. e.preventDefault();
  15518. if (this._leftJoystick === true) {
  15519. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15520. } else {
  15521. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15522. }
  15523. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15524. this._joystickPointerID = e.pointerId;
  15525. this._joystickPointerStartPos.x = e.clientX;
  15526. this._joystickPointerStartPos.y = e.clientY;
  15527. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15528. this._deltaJoystickVector.x = 0;
  15529. this._deltaJoystickVector.y = 0;
  15530. this.pressed = true;
  15531. this._touches.add(e.pointerId.toString(), e);
  15532. } else {
  15533. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15534. this._action();
  15535. this._touches.add(e.pointerId.toString(), e);
  15536. }
  15537. }
  15538. };
  15539. VirtualJoystick.prototype._onPointerMove = function (e) {
  15540. if (this._joystickPointerID == e.pointerId) {
  15541. this._joystickPointerPos.x = e.clientX;
  15542. this._joystickPointerPos.y = e.clientY;
  15543. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15544. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15545. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15546. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15547. switch (this._axisTargetedByLeftAndRight) {
  15548. case 0 /* X */:
  15549. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15550. break;
  15551. case 1 /* Y */:
  15552. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15553. break;
  15554. case 2 /* Z */:
  15555. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15556. break;
  15557. }
  15558. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15559. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15560. switch (this._axisTargetedByUpAndDown) {
  15561. case 0 /* X */:
  15562. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15563. break;
  15564. case 1 /* Y */:
  15565. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15566. break;
  15567. case 2 /* Z */:
  15568. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15569. break;
  15570. }
  15571. } else {
  15572. if (this._touches.item(e.pointerId.toString())) {
  15573. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15574. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15575. }
  15576. }
  15577. };
  15578. VirtualJoystick.prototype._onPointerUp = function (e) {
  15579. this._clearCanvas();
  15580. if (this._joystickPointerID == e.pointerId) {
  15581. this._joystickPointerID = -1;
  15582. this.pressed = false;
  15583. }
  15584. this._deltaJoystickVector.x = 0;
  15585. this._deltaJoystickVector.y = 0;
  15586. this._touches.remove(e.pointerId.toString());
  15587. };
  15588. /**
  15589. * Change the color of the virtual joystick
  15590. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15591. */
  15592. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15593. this._joystickColor = newColor;
  15594. };
  15595. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15596. this._action = action;
  15597. };
  15598. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15599. switch (axis) {
  15600. case 0 /* X */:
  15601. case 1 /* Y */:
  15602. case 2 /* Z */:
  15603. this._axisTargetedByLeftAndRight = axis;
  15604. break;
  15605. default:
  15606. this._axisTargetedByLeftAndRight = 0 /* X */;
  15607. break;
  15608. }
  15609. };
  15610. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15611. switch (axis) {
  15612. case 0 /* X */:
  15613. case 1 /* Y */:
  15614. case 2 /* Z */:
  15615. this._axisTargetedByUpAndDown = axis;
  15616. break;
  15617. default:
  15618. this._axisTargetedByUpAndDown = 1 /* Y */;
  15619. break;
  15620. }
  15621. };
  15622. VirtualJoystick.prototype._clearCanvas = function () {
  15623. if (this._leftJoystick) {
  15624. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15625. } else {
  15626. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15627. }
  15628. };
  15629. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15630. var _this = this;
  15631. if (this.pressed) {
  15632. this._clearCanvas();
  15633. this._touches.forEach(function (touch) {
  15634. if (touch.pointerId === _this._joystickPointerID) {
  15635. VirtualJoystick.vjCanvasContext.beginPath();
  15636. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15637. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15638. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15639. VirtualJoystick.vjCanvasContext.stroke();
  15640. VirtualJoystick.vjCanvasContext.beginPath();
  15641. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15642. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15643. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15644. VirtualJoystick.vjCanvasContext.stroke();
  15645. VirtualJoystick.vjCanvasContext.beginPath();
  15646. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15647. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15648. VirtualJoystick.vjCanvasContext.stroke();
  15649. } else {
  15650. VirtualJoystick.vjCanvasContext.beginPath();
  15651. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15652. VirtualJoystick.vjCanvasContext.beginPath();
  15653. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15654. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15655. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15656. VirtualJoystick.vjCanvasContext.stroke();
  15657. }
  15658. ;
  15659. });
  15660. }
  15661. requestAnimationFrame(function () {
  15662. _this._drawVirtualJoystick();
  15663. });
  15664. };
  15665. VirtualJoystick.prototype.releaseCanvas = function () {
  15666. if (VirtualJoystick.vjCanvas) {
  15667. document.body.removeChild(VirtualJoystick.vjCanvas);
  15668. VirtualJoystick.vjCanvas = null;
  15669. }
  15670. };
  15671. VirtualJoystick._globalJoystickIndex = 0;
  15672. return VirtualJoystick;
  15673. })();
  15674. BABYLON.VirtualJoystick = VirtualJoystick;
  15675. })(BABYLON || (BABYLON = {}));
  15676. var BABYLON;
  15677. (function (BABYLON) {
  15678. (function (VirtualJoystick) {
  15679. var Collection = (function () {
  15680. function Collection() {
  15681. this._count = 0;
  15682. this._collection = new Array();
  15683. }
  15684. Collection.prototype.Count = function () {
  15685. return this._count;
  15686. };
  15687. Collection.prototype.add = function (key, item) {
  15688. if (this._collection[key] != undefined) {
  15689. return undefined;
  15690. }
  15691. this._collection[key] = item;
  15692. return ++this._count;
  15693. };
  15694. Collection.prototype.remove = function (key) {
  15695. if (this._collection[key] == undefined) {
  15696. return undefined;
  15697. }
  15698. delete this._collection[key];
  15699. return --this._count;
  15700. };
  15701. Collection.prototype.item = function (key) {
  15702. return this._collection[key];
  15703. };
  15704. Collection.prototype.forEach = function (block) {
  15705. var key;
  15706. for (key in this._collection) {
  15707. if (this._collection.hasOwnProperty(key)) {
  15708. block(this._collection[key]);
  15709. }
  15710. }
  15711. };
  15712. return Collection;
  15713. })();
  15714. VirtualJoystick.Collection = Collection;
  15715. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15716. var VirtualJoystick = BABYLON.VirtualJoystick;
  15717. })(BABYLON || (BABYLON = {}));
  15718. var __extends = this.__extends || function (d, b) {
  15719. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15720. function __() { this.constructor = d; }
  15721. __.prototype = b.prototype;
  15722. d.prototype = new __();
  15723. };
  15724. var BABYLON;
  15725. (function (BABYLON) {
  15726. var OculusRiftDevKit2013_Metric = {
  15727. HResolution: 1280,
  15728. VResolution: 800,
  15729. HScreenSize: 0.149759993,
  15730. VScreenSize: 0.0935999975,
  15731. VScreenCenter: 0.0467999987,
  15732. EyeToScreenDistance: 0.0410000011,
  15733. LensSeparationDistance: 0.0635000020,
  15734. InterpupillaryDistance: 0.0640000030,
  15735. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15736. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15737. PostProcessScaleFactor: 1.714605507808412,
  15738. LensCenterOffset: 0.151976421
  15739. };
  15740. var _OculusInnerCamera = (function (_super) {
  15741. __extends(_OculusInnerCamera, _super);
  15742. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15743. _super.call(this, name, position, scene);
  15744. this._workMatrix = new BABYLON.Matrix();
  15745. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15746. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15747. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15748. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15749. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15750. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15751. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15752. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15753. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15754. }
  15755. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15756. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15757. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15758. return this._projectionMatrix;
  15759. };
  15760. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15761. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15762. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15763. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15764. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15765. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15766. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15767. return this._viewMatrix;
  15768. };
  15769. return _OculusInnerCamera;
  15770. })(BABYLON.FreeCamera);
  15771. var OculusCamera = (function (_super) {
  15772. __extends(OculusCamera, _super);
  15773. function OculusCamera(name, position, scene) {
  15774. _super.call(this, name, position, scene);
  15775. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15776. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15777. this.subCameras.push(this._leftCamera);
  15778. this.subCameras.push(this._rightCamera);
  15779. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15780. }
  15781. OculusCamera.prototype._update = function () {
  15782. this._leftCamera.position.copyFrom(this.position);
  15783. this._rightCamera.position.copyFrom(this.position);
  15784. this._updateCamera(this._leftCamera);
  15785. this._updateCamera(this._rightCamera);
  15786. _super.prototype._update.call(this);
  15787. };
  15788. OculusCamera.prototype._updateCamera = function (camera) {
  15789. camera.minZ = this.minZ;
  15790. camera.maxZ = this.maxZ;
  15791. camera.rotation.x = this.rotation.x;
  15792. camera.rotation.y = this.rotation.y;
  15793. camera.rotation.z = this.rotation.z;
  15794. };
  15795. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15796. var yaw = evt.alpha / 180 * Math.PI;
  15797. var pitch = evt.beta / 180 * Math.PI;
  15798. var roll = evt.gamma / 180 * Math.PI;
  15799. if (!this._offsetOrientation) {
  15800. this._offsetOrientation = {
  15801. yaw: yaw,
  15802. pitch: pitch,
  15803. roll: roll
  15804. };
  15805. return;
  15806. } else {
  15807. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15808. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15809. this.rotation.z += this._offsetOrientation.roll - roll;
  15810. this._offsetOrientation.yaw = yaw;
  15811. this._offsetOrientation.pitch = pitch;
  15812. this._offsetOrientation.roll = roll;
  15813. }
  15814. };
  15815. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15816. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15817. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15818. };
  15819. OculusCamera.prototype.detachControl = function (element) {
  15820. _super.prototype.detachControl.call(this, element);
  15821. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15822. };
  15823. return OculusCamera;
  15824. })(BABYLON.FreeCamera);
  15825. BABYLON.OculusCamera = OculusCamera;
  15826. })(BABYLON || (BABYLON = {}));
  15827. var __extends = this.__extends || function (d, b) {
  15828. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15829. function __() { this.constructor = d; }
  15830. __.prototype = b.prototype;
  15831. d.prototype = new __();
  15832. };
  15833. var BABYLON;
  15834. (function (BABYLON) {
  15835. var VirtualJoysticksCamera = (function (_super) {
  15836. __extends(VirtualJoysticksCamera, _super);
  15837. function VirtualJoysticksCamera(name, position, scene) {
  15838. _super.call(this, name, position, scene);
  15839. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15840. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15841. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15842. this._leftjoystick.setJoystickSensibility(0.15);
  15843. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15844. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15845. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15846. this._rightjoystick.reverseUpDown = true;
  15847. this._rightjoystick.setJoystickSensibility(0.05);
  15848. this._rightjoystick.setJoystickColor("yellow");
  15849. }
  15850. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15851. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15852. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15853. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15854. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15855. if (!this._leftjoystick.pressed) {
  15856. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15857. }
  15858. if (!this._rightjoystick.pressed) {
  15859. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15860. }
  15861. };
  15862. VirtualJoysticksCamera.prototype.dispose = function () {
  15863. this._leftjoystick.releaseCanvas();
  15864. _super.prototype.dispose.call(this);
  15865. };
  15866. return VirtualJoysticksCamera;
  15867. })(BABYLON.FreeCamera);
  15868. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15869. })(BABYLON || (BABYLON = {}));
  15870. var __extends = this.__extends || function (d, b) {
  15871. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15872. function __() { this.constructor = d; }
  15873. __.prototype = b.prototype;
  15874. d.prototype = new __();
  15875. };
  15876. var BABYLON;
  15877. (function (BABYLON) {
  15878. var ShaderMaterial = (function (_super) {
  15879. __extends(ShaderMaterial, _super);
  15880. function ShaderMaterial(name, scene, shaderPath, options) {
  15881. _super.call(this, name, scene);
  15882. this._textures = new Array();
  15883. this._floats = new Array();
  15884. this._floatsArrays = {};
  15885. this._colors3 = new Array();
  15886. this._colors4 = new Array();
  15887. this._vectors2 = new Array();
  15888. this._vectors3 = new Array();
  15889. this._matrices = new Array();
  15890. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15891. this._shaderPath = shaderPath;
  15892. options.needAlphaBlending = options.needAlphaBlending || false;
  15893. options.needAlphaTesting = options.needAlphaTesting || false;
  15894. options.attributes = options.attributes || ["position", "normal", "uv"];
  15895. options.uniforms = options.uniforms || ["worldViewProjection"];
  15896. options.samplers = options.samplers || [];
  15897. this._options = options;
  15898. }
  15899. ShaderMaterial.prototype.needAlphaBlending = function () {
  15900. return this._options.needAlphaBlending;
  15901. };
  15902. ShaderMaterial.prototype.needAlphaTesting = function () {
  15903. return this._options.needAlphaTesting;
  15904. };
  15905. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15906. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15907. this._options.uniforms.push(uniformName);
  15908. }
  15909. };
  15910. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15911. if (this._options.samplers.indexOf(name) === -1) {
  15912. this._options.samplers.push(name);
  15913. }
  15914. this._textures[name] = texture;
  15915. return this;
  15916. };
  15917. ShaderMaterial.prototype.setFloat = function (name, value) {
  15918. this._checkUniform(name);
  15919. this._floats[name] = value;
  15920. return this;
  15921. };
  15922. ShaderMaterial.prototype.setFloats = function (name, value) {
  15923. this._checkUniform(name);
  15924. this._floatsArrays[name] = value;
  15925. return this;
  15926. };
  15927. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15928. this._checkUniform(name);
  15929. this._colors3[name] = value;
  15930. return this;
  15931. };
  15932. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15933. this._checkUniform(name);
  15934. this._colors4[name] = value;
  15935. return this;
  15936. };
  15937. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15938. this._checkUniform(name);
  15939. this._vectors2[name] = value;
  15940. return this;
  15941. };
  15942. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15943. this._checkUniform(name);
  15944. this._vectors3[name] = value;
  15945. return this;
  15946. };
  15947. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15948. this._checkUniform(name);
  15949. this._matrices[name] = value;
  15950. return this;
  15951. };
  15952. ShaderMaterial.prototype.isReady = function () {
  15953. var engine = this.getScene().getEngine();
  15954. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15955. if (!this._effect.isReady()) {
  15956. return false;
  15957. }
  15958. return true;
  15959. };
  15960. ShaderMaterial.prototype.bind = function (world) {
  15961. if (this._options.uniforms.indexOf("world") !== -1) {
  15962. this._effect.setMatrix("world", world);
  15963. }
  15964. if (this._options.uniforms.indexOf("view") !== -1) {
  15965. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15966. }
  15967. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15968. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15969. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15970. }
  15971. if (this._options.uniforms.indexOf("projection") !== -1) {
  15972. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15973. }
  15974. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15975. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15976. }
  15977. for (var name in this._textures) {
  15978. this._effect.setTexture(name, this._textures[name]);
  15979. }
  15980. for (name in this._floats) {
  15981. this._effect.setFloat(name, this._floats[name]);
  15982. }
  15983. for (name in this._floatsArrays) {
  15984. this._effect.setArray(name, this._floatsArrays[name]);
  15985. }
  15986. for (name in this._colors3) {
  15987. this._effect.setColor3(name, this._colors3[name]);
  15988. }
  15989. for (name in this._colors4) {
  15990. var color = this._colors4[name];
  15991. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15992. }
  15993. for (name in this._vectors2) {
  15994. this._effect.setVector2(name, this._vectors2[name]);
  15995. }
  15996. for (name in this._vectors3) {
  15997. this._effect.setVector3(name, this._vectors3[name]);
  15998. }
  15999. for (name in this._matrices) {
  16000. this._effect.setMatrix(name, this._matrices[name]);
  16001. }
  16002. };
  16003. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16004. for (var name in this._textures) {
  16005. this._textures[name].dispose();
  16006. }
  16007. this._textures = [];
  16008. _super.prototype.dispose.call(this, forceDisposeEffect);
  16009. };
  16010. return ShaderMaterial;
  16011. })(BABYLON.Material);
  16012. BABYLON.ShaderMaterial = ShaderMaterial;
  16013. })(BABYLON || (BABYLON = {}));
  16014. var BABYLON;
  16015. (function (BABYLON) {
  16016. var VertexData = (function () {
  16017. function VertexData() {
  16018. }
  16019. VertexData.prototype.set = function (data, kind) {
  16020. switch (kind) {
  16021. case BABYLON.VertexBuffer.PositionKind:
  16022. this.positions = data;
  16023. break;
  16024. case BABYLON.VertexBuffer.NormalKind:
  16025. this.normals = data;
  16026. break;
  16027. case BABYLON.VertexBuffer.UVKind:
  16028. this.uvs = data;
  16029. break;
  16030. case BABYLON.VertexBuffer.UV2Kind:
  16031. this.uv2s = data;
  16032. break;
  16033. case BABYLON.VertexBuffer.ColorKind:
  16034. this.colors = data;
  16035. break;
  16036. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16037. this.matricesIndices = data;
  16038. break;
  16039. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16040. this.matricesWeights = data;
  16041. break;
  16042. }
  16043. };
  16044. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16045. this._applyTo(mesh, updatable);
  16046. };
  16047. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16048. this._applyTo(geometry, updatable);
  16049. };
  16050. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16051. this._update(mesh);
  16052. };
  16053. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16054. this._update(geometry);
  16055. };
  16056. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16057. if (this.positions) {
  16058. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16059. }
  16060. if (this.normals) {
  16061. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16062. }
  16063. if (this.uvs) {
  16064. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16065. }
  16066. if (this.uv2s) {
  16067. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16068. }
  16069. if (this.colors) {
  16070. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16071. }
  16072. if (this.matricesIndices) {
  16073. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16074. }
  16075. if (this.matricesWeights) {
  16076. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16077. }
  16078. if (this.indices) {
  16079. meshOrGeometry.setIndices(this.indices);
  16080. }
  16081. };
  16082. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16083. if (this.positions) {
  16084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16085. }
  16086. if (this.normals) {
  16087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16088. }
  16089. if (this.uvs) {
  16090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16091. }
  16092. if (this.uv2s) {
  16093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16094. }
  16095. if (this.colors) {
  16096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16097. }
  16098. if (this.matricesIndices) {
  16099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16100. }
  16101. if (this.matricesWeights) {
  16102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16103. }
  16104. if (this.indices) {
  16105. meshOrGeometry.setIndices(this.indices);
  16106. }
  16107. };
  16108. VertexData.prototype.transform = function (matrix) {
  16109. var transformed = BABYLON.Vector3.Zero();
  16110. if (this.positions) {
  16111. var position = BABYLON.Vector3.Zero();
  16112. for (var index = 0; index < this.positions.length; index += 3) {
  16113. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16114. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16115. this.positions[index] = transformed.x;
  16116. this.positions[index + 1] = transformed.y;
  16117. this.positions[index + 2] = transformed.z;
  16118. }
  16119. }
  16120. if (this.normals) {
  16121. var normal = BABYLON.Vector3.Zero();
  16122. for (index = 0; index < this.normals.length; index += 3) {
  16123. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16124. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16125. this.normals[index] = transformed.x;
  16126. this.normals[index + 1] = transformed.y;
  16127. this.normals[index + 2] = transformed.z;
  16128. }
  16129. }
  16130. };
  16131. VertexData.prototype.merge = function (other) {
  16132. if (other.indices) {
  16133. if (!this.indices) {
  16134. this.indices = [];
  16135. }
  16136. var offset = this.positions ? this.positions.length / 3 : 0;
  16137. for (var index = 0; index < other.indices.length; index++) {
  16138. this.indices.push(other.indices[index] + offset);
  16139. }
  16140. }
  16141. if (other.positions) {
  16142. if (!this.positions) {
  16143. this.positions = [];
  16144. }
  16145. for (index = 0; index < other.positions.length; index++) {
  16146. this.positions.push(other.positions[index]);
  16147. }
  16148. }
  16149. if (other.normals) {
  16150. if (!this.normals) {
  16151. this.normals = [];
  16152. }
  16153. for (index = 0; index < other.normals.length; index++) {
  16154. this.normals.push(other.normals[index]);
  16155. }
  16156. }
  16157. if (other.uvs) {
  16158. if (!this.uvs) {
  16159. this.uvs = [];
  16160. }
  16161. for (index = 0; index < other.uvs.length; index++) {
  16162. this.uvs.push(other.uvs[index]);
  16163. }
  16164. }
  16165. if (other.uv2s) {
  16166. if (!this.uv2s) {
  16167. this.uv2s = [];
  16168. }
  16169. for (index = 0; index < other.uv2s.length; index++) {
  16170. this.uv2s.push(other.uv2s[index]);
  16171. }
  16172. }
  16173. if (other.matricesIndices) {
  16174. if (!this.matricesIndices) {
  16175. this.matricesIndices = [];
  16176. }
  16177. for (index = 0; index < other.matricesIndices.length; index++) {
  16178. this.matricesIndices.push(other.matricesIndices[index]);
  16179. }
  16180. }
  16181. if (other.matricesWeights) {
  16182. if (!this.matricesWeights) {
  16183. this.matricesWeights = [];
  16184. }
  16185. for (index = 0; index < other.matricesWeights.length; index++) {
  16186. this.matricesWeights.push(other.matricesWeights[index]);
  16187. }
  16188. }
  16189. if (other.colors) {
  16190. if (!this.colors) {
  16191. this.colors = [];
  16192. }
  16193. for (index = 0; index < other.colors.length; index++) {
  16194. this.colors.push(other.colors[index]);
  16195. }
  16196. }
  16197. };
  16198. VertexData.ExtractFromMesh = function (mesh) {
  16199. return VertexData._ExtractFrom(mesh);
  16200. };
  16201. VertexData.ExtractFromGeometry = function (geometry) {
  16202. return VertexData._ExtractFrom(geometry);
  16203. };
  16204. VertexData._ExtractFrom = function (meshOrGeometry) {
  16205. var result = new BABYLON.VertexData();
  16206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16207. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16208. }
  16209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16210. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16211. }
  16212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16213. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16214. }
  16215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16216. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16217. }
  16218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16219. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16220. }
  16221. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16222. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16223. }
  16224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16225. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16226. }
  16227. result.indices = meshOrGeometry.getIndices();
  16228. return result;
  16229. };
  16230. VertexData.CreateBox = function (size) {
  16231. var normalsSource = [
  16232. new BABYLON.Vector3(0, 0, 1),
  16233. new BABYLON.Vector3(0, 0, -1),
  16234. new BABYLON.Vector3(1, 0, 0),
  16235. new BABYLON.Vector3(-1, 0, 0),
  16236. new BABYLON.Vector3(0, 1, 0),
  16237. new BABYLON.Vector3(0, -1, 0)
  16238. ];
  16239. var indices = [];
  16240. var positions = [];
  16241. var normals = [];
  16242. var uvs = [];
  16243. size = size || 1;
  16244. for (var index = 0; index < normalsSource.length; index++) {
  16245. var normal = normalsSource[index];
  16246. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16247. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16248. var verticesLength = positions.length / 3;
  16249. indices.push(verticesLength);
  16250. indices.push(verticesLength + 1);
  16251. indices.push(verticesLength + 2);
  16252. indices.push(verticesLength);
  16253. indices.push(verticesLength + 2);
  16254. indices.push(verticesLength + 3);
  16255. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16256. positions.push(vertex.x, vertex.y, vertex.z);
  16257. normals.push(normal.x, normal.y, normal.z);
  16258. uvs.push(1.0, 1.0);
  16259. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16260. positions.push(vertex.x, vertex.y, vertex.z);
  16261. normals.push(normal.x, normal.y, normal.z);
  16262. uvs.push(0.0, 1.0);
  16263. vertex = normal.add(side1).add(side2).scale(size / 2);
  16264. positions.push(vertex.x, vertex.y, vertex.z);
  16265. normals.push(normal.x, normal.y, normal.z);
  16266. uvs.push(0.0, 0.0);
  16267. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16268. positions.push(vertex.x, vertex.y, vertex.z);
  16269. normals.push(normal.x, normal.y, normal.z);
  16270. uvs.push(1.0, 0.0);
  16271. }
  16272. var vertexData = new BABYLON.VertexData();
  16273. vertexData.indices = indices;
  16274. vertexData.positions = positions;
  16275. vertexData.normals = normals;
  16276. vertexData.uvs = uvs;
  16277. return vertexData;
  16278. };
  16279. VertexData.CreateSphere = function (segments, diameter) {
  16280. segments = segments || 32;
  16281. diameter = diameter || 1;
  16282. var radius = diameter / 2;
  16283. var totalZRotationSteps = 2 + segments;
  16284. var totalYRotationSteps = 2 * totalZRotationSteps;
  16285. var indices = [];
  16286. var positions = [];
  16287. var normals = [];
  16288. var uvs = [];
  16289. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16290. var normalizedZ = zRotationStep / totalZRotationSteps;
  16291. var angleZ = (normalizedZ * Math.PI);
  16292. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16293. var normalizedY = yRotationStep / totalYRotationSteps;
  16294. var angleY = normalizedY * Math.PI * 2;
  16295. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16296. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16297. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16298. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16299. var vertex = complete.scale(radius);
  16300. var normal = BABYLON.Vector3.Normalize(vertex);
  16301. positions.push(vertex.x, vertex.y, vertex.z);
  16302. normals.push(normal.x, normal.y, normal.z);
  16303. uvs.push(normalizedZ, normalizedY);
  16304. }
  16305. if (zRotationStep > 0) {
  16306. var verticesCount = positions.length / 3;
  16307. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16308. indices.push((firstIndex));
  16309. indices.push((firstIndex + 1));
  16310. indices.push(firstIndex + totalYRotationSteps + 1);
  16311. indices.push((firstIndex + totalYRotationSteps + 1));
  16312. indices.push((firstIndex + 1));
  16313. indices.push((firstIndex + totalYRotationSteps + 2));
  16314. }
  16315. }
  16316. }
  16317. var vertexData = new BABYLON.VertexData();
  16318. vertexData.indices = indices;
  16319. vertexData.positions = positions;
  16320. vertexData.normals = normals;
  16321. vertexData.uvs = uvs;
  16322. return vertexData;
  16323. };
  16324. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16325. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16326. var radiusTop = diameterTop / 2;
  16327. var radiusBottom = diameterBottom / 2;
  16328. var indices = [];
  16329. var positions = [];
  16330. var normals = [];
  16331. var uvs = [];
  16332. height = height || 1;
  16333. diameterTop = diameterTop || 0.5;
  16334. diameterBottom = diameterBottom || 1;
  16335. tessellation = tessellation || 16;
  16336. subdivisions = subdivisions || 1;
  16337. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16338. var getCircleVector = function (i) {
  16339. var angle = (i * 2.0 * Math.PI / tessellation);
  16340. var dx = Math.cos(angle);
  16341. var dz = Math.sin(angle);
  16342. return new BABYLON.Vector3(dx, 0, dz);
  16343. };
  16344. var createCylinderCap = function (isTop) {
  16345. var radius = isTop ? radiusTop : radiusBottom;
  16346. if (radius == 0) {
  16347. return;
  16348. }
  16349. var vbase = positions.length / 3;
  16350. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16351. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16352. if (!isTop) {
  16353. offset.scaleInPlace(-1);
  16354. textureScale.x = -textureScale.x;
  16355. }
  16356. for (i = 0; i < tessellation; i++) {
  16357. var circleVector = getCircleVector(i);
  16358. var position = circleVector.scale(radius).add(offset);
  16359. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16360. positions.push(position.x, position.y, position.z);
  16361. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16362. }
  16363. for (var i = 0; i < tessellation - 2; i++) {
  16364. if (!isTop) {
  16365. indices.push(vbase);
  16366. indices.push(vbase + (i + 2) % tessellation);
  16367. indices.push(vbase + (i + 1) % tessellation);
  16368. } else {
  16369. indices.push(vbase);
  16370. indices.push(vbase + (i + 1) % tessellation);
  16371. indices.push(vbase + (i + 2) % tessellation);
  16372. }
  16373. }
  16374. };
  16375. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16376. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16377. var stride = tessellation + 1;
  16378. for (var i = 0; i <= tessellation; i++) {
  16379. var circleVector = getCircleVector(i);
  16380. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16381. var position, radius = radiusBottom;
  16382. for (var s = 0; s <= subdivisions; s++) {
  16383. position = circleVector.scale(radius);
  16384. position.addInPlace(base.add(offset.scale(s)));
  16385. textureCoordinate.y += 1 / subdivisions;
  16386. radius += (radiusTop - radiusBottom) / subdivisions;
  16387. positions.push(position.x, position.y, position.z);
  16388. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16389. }
  16390. }
  16391. subdivisions += 1;
  16392. for (var s = 0; s < subdivisions - 1; s++) {
  16393. for (var i = 0; i <= tessellation; i++) {
  16394. indices.push(i * subdivisions + s);
  16395. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16396. indices.push(i * subdivisions + (s + 1));
  16397. indices.push(i * subdivisions + (s + 1));
  16398. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16399. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16400. }
  16401. }
  16402. createCylinderCap(true);
  16403. createCylinderCap(false);
  16404. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16405. var vertexData = new BABYLON.VertexData();
  16406. vertexData.indices = indices;
  16407. vertexData.positions = positions;
  16408. vertexData.normals = normals;
  16409. vertexData.uvs = uvs;
  16410. return vertexData;
  16411. };
  16412. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16413. var indices = [];
  16414. var positions = [];
  16415. var normals = [];
  16416. var uvs = [];
  16417. diameter = diameter || 1;
  16418. thickness = thickness || 0.5;
  16419. tessellation = tessellation || 16;
  16420. var stride = tessellation + 1;
  16421. for (var i = 0; i <= tessellation; i++) {
  16422. var u = i / tessellation;
  16423. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16424. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16425. for (var j = 0; j <= tessellation; j++) {
  16426. var v = 1 - j / tessellation;
  16427. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16428. var dx = Math.cos(innerAngle);
  16429. var dy = Math.sin(innerAngle);
  16430. var normal = new BABYLON.Vector3(dx, dy, 0);
  16431. var position = normal.scale(thickness / 2);
  16432. var textureCoordinate = new BABYLON.Vector2(u, v);
  16433. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16434. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16435. positions.push(position.x, position.y, position.z);
  16436. normals.push(normal.x, normal.y, normal.z);
  16437. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16438. var nextI = (i + 1) % stride;
  16439. var nextJ = (j + 1) % stride;
  16440. indices.push(i * stride + j);
  16441. indices.push(i * stride + nextJ);
  16442. indices.push(nextI * stride + j);
  16443. indices.push(i * stride + nextJ);
  16444. indices.push(nextI * stride + nextJ);
  16445. indices.push(nextI * stride + j);
  16446. }
  16447. }
  16448. var vertexData = new BABYLON.VertexData();
  16449. vertexData.indices = indices;
  16450. vertexData.positions = positions;
  16451. vertexData.normals = normals;
  16452. vertexData.uvs = uvs;
  16453. return vertexData;
  16454. };
  16455. VertexData.CreateLines = function (points) {
  16456. var indices = [];
  16457. var positions = [];
  16458. for (var index = 0; index < points.length; index++) {
  16459. positions.push(points[index].x, points[index].y, points[index].z);
  16460. if (index > 0) {
  16461. indices.push(index - 1);
  16462. indices.push(index);
  16463. }
  16464. }
  16465. var vertexData = new BABYLON.VertexData();
  16466. vertexData.indices = indices;
  16467. vertexData.positions = positions;
  16468. return vertexData;
  16469. };
  16470. VertexData.CreateGround = function (width, height, subdivisions) {
  16471. var indices = [];
  16472. var positions = [];
  16473. var normals = [];
  16474. var uvs = [];
  16475. var row, col;
  16476. width = width || 1;
  16477. height = height || 1;
  16478. subdivisions = subdivisions || 1;
  16479. for (row = 0; row <= subdivisions; row++) {
  16480. for (col = 0; col <= subdivisions; col++) {
  16481. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16482. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16483. positions.push(position.x, position.y, position.z);
  16484. normals.push(normal.x, normal.y, normal.z);
  16485. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16486. }
  16487. }
  16488. for (row = 0; row < subdivisions; row++) {
  16489. for (col = 0; col < subdivisions; col++) {
  16490. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16491. indices.push(col + 1 + row * (subdivisions + 1));
  16492. indices.push(col + row * (subdivisions + 1));
  16493. indices.push(col + (row + 1) * (subdivisions + 1));
  16494. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16495. indices.push(col + row * (subdivisions + 1));
  16496. }
  16497. }
  16498. var vertexData = new BABYLON.VertexData();
  16499. vertexData.indices = indices;
  16500. vertexData.positions = positions;
  16501. vertexData.normals = normals;
  16502. vertexData.uvs = uvs;
  16503. return vertexData;
  16504. };
  16505. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16506. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16507. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16508. var indices = [];
  16509. var positions = [];
  16510. var normals = [];
  16511. var uvs = [];
  16512. var row, col, tileRow, tileCol;
  16513. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16514. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16515. precision.w = (precision.w < 1) ? 1 : precision.w;
  16516. precision.h = (precision.h < 1) ? 1 : precision.h;
  16517. var tileSize = {
  16518. 'w': (xmax - xmin) / subdivisions.w,
  16519. 'h': (zmax - zmin) / subdivisions.h
  16520. };
  16521. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16522. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16523. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16524. }
  16525. }
  16526. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16527. var base = positions.length / 3;
  16528. var rowLength = precision.w + 1;
  16529. for (row = 0; row < precision.h; row++) {
  16530. for (col = 0; col < precision.w; col++) {
  16531. var square = [
  16532. base + col + row * rowLength,
  16533. base + (col + 1) + row * rowLength,
  16534. base + (col + 1) + (row + 1) * rowLength,
  16535. base + col + (row + 1) * rowLength
  16536. ];
  16537. indices.push(square[1]);
  16538. indices.push(square[2]);
  16539. indices.push(square[3]);
  16540. indices.push(square[0]);
  16541. indices.push(square[1]);
  16542. indices.push(square[3]);
  16543. }
  16544. }
  16545. var position = BABYLON.Vector3.Zero();
  16546. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16547. for (row = 0; row <= precision.h; row++) {
  16548. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16549. for (col = 0; col <= precision.w; col++) {
  16550. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16551. position.y = 0;
  16552. positions.push(position.x, position.y, position.z);
  16553. normals.push(normal.x, normal.y, normal.z);
  16554. uvs.push(col / precision.w, row / precision.h);
  16555. }
  16556. }
  16557. }
  16558. var vertexData = new BABYLON.VertexData();
  16559. vertexData.indices = indices;
  16560. vertexData.positions = positions;
  16561. vertexData.normals = normals;
  16562. vertexData.uvs = uvs;
  16563. return vertexData;
  16564. };
  16565. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16566. var indices = [];
  16567. var positions = [];
  16568. var normals = [];
  16569. var uvs = [];
  16570. var row, col;
  16571. for (row = 0; row <= subdivisions; row++) {
  16572. for (col = 0; col <= subdivisions; col++) {
  16573. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16574. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16575. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16576. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16577. var r = buffer[pos] / 255.0;
  16578. var g = buffer[pos + 1] / 255.0;
  16579. var b = buffer[pos + 2] / 255.0;
  16580. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16581. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16582. positions.push(position.x, position.y, position.z);
  16583. normals.push(0, 0, 0);
  16584. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16585. }
  16586. }
  16587. for (row = 0; row < subdivisions; row++) {
  16588. for (col = 0; col < subdivisions; col++) {
  16589. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16590. indices.push(col + 1 + row * (subdivisions + 1));
  16591. indices.push(col + row * (subdivisions + 1));
  16592. indices.push(col + (row + 1) * (subdivisions + 1));
  16593. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16594. indices.push(col + row * (subdivisions + 1));
  16595. }
  16596. }
  16597. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16598. var vertexData = new BABYLON.VertexData();
  16599. vertexData.indices = indices;
  16600. vertexData.positions = positions;
  16601. vertexData.normals = normals;
  16602. vertexData.uvs = uvs;
  16603. return vertexData;
  16604. };
  16605. VertexData.CreatePlane = function (size) {
  16606. var indices = [];
  16607. var positions = [];
  16608. var normals = [];
  16609. var uvs = [];
  16610. size = size || 1;
  16611. var halfSize = size / 2.0;
  16612. positions.push(-halfSize, -halfSize, 0);
  16613. normals.push(0, 0, -1.0);
  16614. uvs.push(0.0, 0.0);
  16615. positions.push(halfSize, -halfSize, 0);
  16616. normals.push(0, 0, -1.0);
  16617. uvs.push(1.0, 0.0);
  16618. positions.push(halfSize, halfSize, 0);
  16619. normals.push(0, 0, -1.0);
  16620. uvs.push(1.0, 1.0);
  16621. positions.push(-halfSize, halfSize, 0);
  16622. normals.push(0, 0, -1.0);
  16623. uvs.push(0.0, 1.0);
  16624. indices.push(0);
  16625. indices.push(1);
  16626. indices.push(2);
  16627. indices.push(0);
  16628. indices.push(2);
  16629. indices.push(3);
  16630. var vertexData = new BABYLON.VertexData();
  16631. vertexData.indices = indices;
  16632. vertexData.positions = positions;
  16633. vertexData.normals = normals;
  16634. vertexData.uvs = uvs;
  16635. return vertexData;
  16636. };
  16637. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16638. var indices = [];
  16639. var positions = [];
  16640. var normals = [];
  16641. var uvs = [];
  16642. radius = radius || 2;
  16643. tube = tube || 0.5;
  16644. radialSegments = radialSegments || 32;
  16645. tubularSegments = tubularSegments || 32;
  16646. p = p || 2;
  16647. q = q || 3;
  16648. var getPos = function (angle) {
  16649. var cu = Math.cos(angle);
  16650. var su = Math.sin(angle);
  16651. var quOverP = q / p * angle;
  16652. var cs = Math.cos(quOverP);
  16653. var tx = radius * (2 + cs) * 0.5 * cu;
  16654. var ty = radius * (2 + cs) * su * 0.5;
  16655. var tz = radius * Math.sin(quOverP) * 0.5;
  16656. return new BABYLON.Vector3(tx, ty, tz);
  16657. };
  16658. for (var i = 0; i <= radialSegments; i++) {
  16659. var modI = i % radialSegments;
  16660. var u = modI / radialSegments * 2 * p * Math.PI;
  16661. var p1 = getPos(u);
  16662. var p2 = getPos(u + 0.01);
  16663. var tang = p2.subtract(p1);
  16664. var n = p2.add(p1);
  16665. var bitan = BABYLON.Vector3.Cross(tang, n);
  16666. n = BABYLON.Vector3.Cross(bitan, tang);
  16667. bitan.normalize();
  16668. n.normalize();
  16669. for (var j = 0; j < tubularSegments; j++) {
  16670. var modJ = j % tubularSegments;
  16671. var v = modJ / tubularSegments * 2 * Math.PI;
  16672. var cx = -tube * Math.cos(v);
  16673. var cy = tube * Math.sin(v);
  16674. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16675. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16676. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16677. uvs.push(i / radialSegments);
  16678. uvs.push(j / tubularSegments);
  16679. }
  16680. }
  16681. for (i = 0; i < radialSegments; i++) {
  16682. for (j = 0; j < tubularSegments; j++) {
  16683. var jNext = (j + 1) % tubularSegments;
  16684. var a = i * tubularSegments + j;
  16685. var b = (i + 1) * tubularSegments + j;
  16686. var c = (i + 1) * tubularSegments + jNext;
  16687. var d = i * tubularSegments + jNext;
  16688. indices.push(d);
  16689. indices.push(b);
  16690. indices.push(a);
  16691. indices.push(d);
  16692. indices.push(c);
  16693. indices.push(b);
  16694. }
  16695. }
  16696. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16697. var vertexData = new BABYLON.VertexData();
  16698. vertexData.indices = indices;
  16699. vertexData.positions = positions;
  16700. vertexData.normals = normals;
  16701. vertexData.uvs = uvs;
  16702. return vertexData;
  16703. };
  16704. VertexData.ComputeNormals = function (positions, indices, normals) {
  16705. var positionVectors = [];
  16706. var facesOfVertices = [];
  16707. var index;
  16708. for (index = 0; index < positions.length; index += 3) {
  16709. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16710. positionVectors.push(vector3);
  16711. facesOfVertices.push([]);
  16712. }
  16713. var facesNormals = [];
  16714. for (index = 0; index < indices.length / 3; index++) {
  16715. var i1 = indices[index * 3];
  16716. var i2 = indices[index * 3 + 1];
  16717. var i3 = indices[index * 3 + 2];
  16718. var p1 = positionVectors[i1];
  16719. var p2 = positionVectors[i2];
  16720. var p3 = positionVectors[i3];
  16721. var p1p2 = p1.subtract(p2);
  16722. var p3p2 = p3.subtract(p2);
  16723. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16724. facesOfVertices[i1].push(index);
  16725. facesOfVertices[i2].push(index);
  16726. facesOfVertices[i3].push(index);
  16727. }
  16728. for (index = 0; index < positionVectors.length; index++) {
  16729. var faces = facesOfVertices[index];
  16730. var normal = BABYLON.Vector3.Zero();
  16731. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16732. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16733. }
  16734. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16735. normals[index * 3] = normal.x;
  16736. normals[index * 3 + 1] = normal.y;
  16737. normals[index * 3 + 2] = normal.z;
  16738. }
  16739. };
  16740. return VertexData;
  16741. })();
  16742. BABYLON.VertexData = VertexData;
  16743. })(BABYLON || (BABYLON = {}));
  16744. var __extends = this.__extends || function (d, b) {
  16745. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16746. function __() { this.constructor = d; }
  16747. __.prototype = b.prototype;
  16748. d.prototype = new __();
  16749. };
  16750. var BABYLON;
  16751. (function (BABYLON) {
  16752. var buildCamera = function (that, name) {
  16753. that._leftCamera.isIntermediate = true;
  16754. that.subCameras.push(that._leftCamera);
  16755. that.subCameras.push(that._rightCamera);
  16756. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16757. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16758. that._anaglyphPostProcess.onApply = function (effect) {
  16759. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16760. };
  16761. that._update();
  16762. };
  16763. var AnaglyphArcRotateCamera = (function (_super) {
  16764. __extends(AnaglyphArcRotateCamera, _super);
  16765. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16766. _super.call(this, name, alpha, beta, radius, target, scene);
  16767. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16768. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16769. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16770. buildCamera(this, name);
  16771. }
  16772. AnaglyphArcRotateCamera.prototype._update = function () {
  16773. this._updateCamera(this._leftCamera);
  16774. this._updateCamera(this._rightCamera);
  16775. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16776. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16777. _super.prototype._update.call(this);
  16778. };
  16779. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16780. camera.beta = this.beta;
  16781. camera.radius = this.radius;
  16782. camera.minZ = this.minZ;
  16783. camera.maxZ = this.maxZ;
  16784. camera.fov = this.fov;
  16785. camera.target = this.target;
  16786. };
  16787. return AnaglyphArcRotateCamera;
  16788. })(BABYLON.ArcRotateCamera);
  16789. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16790. var AnaglyphFreeCamera = (function (_super) {
  16791. __extends(AnaglyphFreeCamera, _super);
  16792. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16793. _super.call(this, name, position, scene);
  16794. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16795. this._transformMatrix = new BABYLON.Matrix();
  16796. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16797. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16798. buildCamera(this, name);
  16799. }
  16800. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16801. var target = this.getTarget();
  16802. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16803. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16804. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16805. };
  16806. AnaglyphFreeCamera.prototype._update = function () {
  16807. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16808. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16809. this._updateCamera(this._leftCamera);
  16810. this._updateCamera(this._rightCamera);
  16811. _super.prototype._update.call(this);
  16812. };
  16813. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16814. camera.minZ = this.minZ;
  16815. camera.maxZ = this.maxZ;
  16816. camera.fov = this.fov;
  16817. camera.viewport = this.viewport;
  16818. camera.setTarget(this.getTarget());
  16819. };
  16820. return AnaglyphFreeCamera;
  16821. })(BABYLON.FreeCamera);
  16822. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16823. })(BABYLON || (BABYLON = {}));
  16824. var __extends = this.__extends || function (d, b) {
  16825. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16826. function __() { this.constructor = d; }
  16827. __.prototype = b.prototype;
  16828. d.prototype = new __();
  16829. };
  16830. var BABYLON;
  16831. (function (BABYLON) {
  16832. var AnaglyphPostProcess = (function (_super) {
  16833. __extends(AnaglyphPostProcess, _super);
  16834. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16835. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16836. }
  16837. return AnaglyphPostProcess;
  16838. })(BABYLON.PostProcess);
  16839. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16840. })(BABYLON || (BABYLON = {}));
  16841. var BABYLON;
  16842. (function (BABYLON) {
  16843. var Tags = (function () {
  16844. function Tags() {
  16845. }
  16846. Tags.EnableFor = function (obj) {
  16847. obj._tags = obj._tags || {};
  16848. obj.hasTags = function () {
  16849. return Tags.HasTags(obj);
  16850. };
  16851. obj.addTags = function (tagsString) {
  16852. return Tags.AddTagsTo(obj, tagsString);
  16853. };
  16854. obj.removeTags = function (tagsString) {
  16855. return Tags.RemoveTagsFrom(obj, tagsString);
  16856. };
  16857. obj.matchesTagsQuery = function (tagsQuery) {
  16858. return Tags.MatchesQuery(obj, tagsQuery);
  16859. };
  16860. };
  16861. Tags.DisableFor = function (obj) {
  16862. delete obj._tags;
  16863. delete obj.hasTags;
  16864. delete obj.addTags;
  16865. delete obj.removeTags;
  16866. delete obj.matchesTagsQuery;
  16867. };
  16868. Tags.HasTags = function (obj) {
  16869. if (!obj._tags) {
  16870. return false;
  16871. }
  16872. return !BABYLON.Tools.IsEmpty(obj._tags);
  16873. };
  16874. Tags.GetTags = function (obj) {
  16875. if (!obj._tags) {
  16876. return null;
  16877. }
  16878. return obj._tags;
  16879. };
  16880. Tags.AddTagsTo = function (obj, tagsString) {
  16881. if (!tagsString) {
  16882. return;
  16883. }
  16884. var tags = tagsString.split(" ");
  16885. for (var t in tags) {
  16886. Tags._AddTagTo(obj, tags[t]);
  16887. }
  16888. };
  16889. Tags._AddTagTo = function (obj, tag) {
  16890. tag = tag.trim();
  16891. if (tag === "" || tag === "true" || tag === "false") {
  16892. return;
  16893. }
  16894. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16895. return;
  16896. }
  16897. Tags.EnableFor(obj);
  16898. obj._tags[tag] = true;
  16899. };
  16900. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16901. if (!Tags.HasTags(obj)) {
  16902. return;
  16903. }
  16904. var tags = tagsString.split(" ");
  16905. for (var t in tags) {
  16906. Tags._RemoveTagFrom(obj, tags[t]);
  16907. }
  16908. };
  16909. Tags._RemoveTagFrom = function (obj, tag) {
  16910. delete obj._tags[tag];
  16911. };
  16912. Tags.MatchesQuery = function (obj, tagsQuery) {
  16913. if (tagsQuery === undefined) {
  16914. return true;
  16915. }
  16916. if (tagsQuery === "") {
  16917. return Tags.HasTags(obj);
  16918. }
  16919. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16920. return Tags.HasTags(obj) && obj._tags[r];
  16921. });
  16922. };
  16923. return Tags;
  16924. })();
  16925. BABYLON.Tags = Tags;
  16926. })(BABYLON || (BABYLON = {}));
  16927. var BABYLON;
  16928. (function (BABYLON) {
  16929. (function (Internals) {
  16930. var AndOrNotEvaluator = (function () {
  16931. function AndOrNotEvaluator() {
  16932. }
  16933. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16934. if (!query.match(/\([^\(\)]*\)/g)) {
  16935. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16936. } else {
  16937. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16938. r = r.slice(1, r.length - 1);
  16939. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16940. });
  16941. }
  16942. if (query === "true") {
  16943. return true;
  16944. }
  16945. if (query === "false") {
  16946. return false;
  16947. }
  16948. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16949. };
  16950. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16951. evaluateCallback = evaluateCallback || (function (r) {
  16952. return r === "true" ? true : false;
  16953. });
  16954. var result;
  16955. var or = parenthesisContent.split("||");
  16956. for (var i in or) {
  16957. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16958. var and = ori.split("&&");
  16959. if (and.length > 1) {
  16960. for (var j = 0; j < and.length; ++j) {
  16961. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16962. if (andj !== "true" && andj !== "false") {
  16963. if (andj[0] === "!") {
  16964. result = !evaluateCallback(andj.substring(1));
  16965. } else {
  16966. result = evaluateCallback(andj);
  16967. }
  16968. } else {
  16969. result = andj === "true" ? true : false;
  16970. }
  16971. if (!result) {
  16972. ori = "false";
  16973. break;
  16974. }
  16975. }
  16976. }
  16977. if (result || ori === "true") {
  16978. result = true;
  16979. break;
  16980. }
  16981. if (ori !== "true" && ori !== "false") {
  16982. if (ori[0] === "!") {
  16983. result = !evaluateCallback(ori.substring(1));
  16984. } else {
  16985. result = evaluateCallback(ori);
  16986. }
  16987. } else {
  16988. result = ori === "true" ? true : false;
  16989. }
  16990. }
  16991. return result ? "true" : "false";
  16992. };
  16993. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16994. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16995. r = r.replace(/[\s]/g, function () {
  16996. return "";
  16997. });
  16998. return r.length % 2 ? "!" : "";
  16999. });
  17000. booleanString = booleanString.trim();
  17001. if (booleanString === "!true") {
  17002. booleanString = "false";
  17003. } else if (booleanString === "!false") {
  17004. booleanString = "true";
  17005. }
  17006. return booleanString;
  17007. };
  17008. return AndOrNotEvaluator;
  17009. })();
  17010. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17011. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17012. var Internals = BABYLON.Internals;
  17013. })(BABYLON || (BABYLON = {}));
  17014. var BABYLON;
  17015. (function (BABYLON) {
  17016. var PostProcessRenderPass = (function () {
  17017. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17018. this._enabled = true;
  17019. this._refCount = 0;
  17020. this._name = name;
  17021. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17022. this.setRenderList(renderList);
  17023. this._renderTexture.onBeforeRender = beforeRender;
  17024. this._renderTexture.onAfterRender = afterRender;
  17025. this._scene = scene;
  17026. }
  17027. PostProcessRenderPass.prototype._incRefCount = function () {
  17028. if (this._refCount === 0) {
  17029. this._scene.customRenderTargets.push(this._renderTexture);
  17030. }
  17031. return ++this._refCount;
  17032. };
  17033. PostProcessRenderPass.prototype._decRefCount = function () {
  17034. this._refCount--;
  17035. if (this._refCount <= 0) {
  17036. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17037. }
  17038. return this._refCount;
  17039. };
  17040. PostProcessRenderPass.prototype._update = function () {
  17041. this.setRenderList(this._renderList);
  17042. };
  17043. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17044. this._renderTexture.renderList = renderList;
  17045. };
  17046. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17047. return this._renderTexture;
  17048. };
  17049. return PostProcessRenderPass;
  17050. })();
  17051. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17052. })(BABYLON || (BABYLON = {}));
  17053. var BABYLON;
  17054. (function (BABYLON) {
  17055. var PostProcessRenderEffect = (function () {
  17056. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  17057. this._engine = engine;
  17058. this._name = name;
  17059. this._postProcessType = postProcessType;
  17060. this._ratio = ratio || 1.0;
  17061. this._samplingMode = samplingMode || null;
  17062. this._singleInstance = singleInstance || true;
  17063. this._cameras = [];
  17064. this._postProcesses = [];
  17065. this._indicesForCamera = [];
  17066. this._renderPasses = [];
  17067. this._renderEffectAsPasses = [];
  17068. this.parameters = function (effect) {
  17069. };
  17070. }
  17071. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  17072. var postProcess;
  17073. var instance;
  17074. var args = [];
  17075. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  17076. for (var i = 0; i < parameters.length; i++) {
  17077. switch (parameters[i]) {
  17078. case "name":
  17079. args[i] = postProcessType.toString();
  17080. break;
  17081. case "ratio":
  17082. args[i] = ratio;
  17083. break;
  17084. case "camera":
  17085. args[i] = null;
  17086. break;
  17087. case "samplingMode":
  17088. args[i] = samplingMode;
  17089. break;
  17090. case "engine":
  17091. args[i] = engine;
  17092. break;
  17093. case "reusable":
  17094. args[i] = true;
  17095. break;
  17096. default:
  17097. args[i] = null;
  17098. break;
  17099. }
  17100. }
  17101. postProcess = function () {
  17102. };
  17103. postProcess.prototype = postProcessType.prototype;
  17104. instance = new postProcess();
  17105. postProcessType.apply(instance, args);
  17106. return instance;
  17107. };
  17108. PostProcessRenderEffect._GetParametersNames = function (func) {
  17109. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  17110. var functWithoutComments = func.toString().replace(commentsRegex, '');
  17111. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  17112. if (parameters === null)
  17113. parameters = [];
  17114. return parameters;
  17115. };
  17116. PostProcessRenderEffect.prototype._update = function () {
  17117. for (var renderPassName in this._renderPasses) {
  17118. this._renderPasses[renderPassName]._update();
  17119. }
  17120. };
  17121. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17122. this._renderPasses[renderPass._name] = renderPass;
  17123. this._linkParameters();
  17124. };
  17125. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17126. delete this._renderPasses[renderPass._name];
  17127. this._linkParameters();
  17128. };
  17129. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17130. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17131. this._linkParameters();
  17132. };
  17133. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17134. for (var renderPassName in this._renderPasses) {
  17135. if (renderPassName === passName) {
  17136. return this._renderPasses[passName];
  17137. }
  17138. }
  17139. };
  17140. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17141. this._renderPasses.length = 0;
  17142. this._linkParameters();
  17143. };
  17144. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17145. var cameraKey;
  17146. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17147. for (var i = 0; i < _cam.length; i++) {
  17148. var camera = _cam[i];
  17149. var cameraName = camera.name;
  17150. if (this._singleInstance) {
  17151. cameraKey = 0;
  17152. } else {
  17153. cameraKey = cameraName;
  17154. }
  17155. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  17156. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17157. if (this._indicesForCamera[cameraName] === null) {
  17158. this._indicesForCamera[cameraName] = [];
  17159. }
  17160. this._indicesForCamera[cameraName].push(index);
  17161. if (this._cameras.indexOf(camera) === -1) {
  17162. this._cameras[cameraName] = camera;
  17163. }
  17164. for (var passName in this._renderPasses) {
  17165. this._renderPasses[passName]._incRefCount();
  17166. }
  17167. }
  17168. this._linkParameters();
  17169. };
  17170. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17171. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17172. for (var i = 0; i < _cam.length; i++) {
  17173. var camera = _cam[i];
  17174. var cameraName = camera.name;
  17175. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17176. var index = this._cameras.indexOf(cameraName);
  17177. this._indicesForCamera.splice(index, 1);
  17178. this._cameras.splice(index, 1);
  17179. for (var passName in this._renderPasses) {
  17180. this._renderPasses[passName]._decRefCount();
  17181. }
  17182. }
  17183. };
  17184. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17185. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17186. for (var i = 0; i < _cam.length; i++) {
  17187. var camera = _cam[i];
  17188. var cameraName = camera.name;
  17189. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17190. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17191. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17192. }
  17193. }
  17194. for (var passName in this._renderPasses) {
  17195. this._renderPasses[passName]._incRefCount();
  17196. }
  17197. }
  17198. };
  17199. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17200. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17201. for (var i = 0; i < _cam.length; i++) {
  17202. var camera = _cam[i];
  17203. var cameraName = camera.Name;
  17204. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17205. for (var passName in this._renderPasses) {
  17206. this._renderPasses[passName]._decRefCount();
  17207. }
  17208. }
  17209. };
  17210. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17211. if (this._singleInstance) {
  17212. return this._postProcesses[0];
  17213. } else {
  17214. return this._postProcesses[camera.name];
  17215. }
  17216. };
  17217. PostProcessRenderEffect.prototype._linkParameters = function () {
  17218. var _this = this;
  17219. for (var index in this._postProcesses) {
  17220. this._postProcesses[index].onApply = function (effect) {
  17221. _this.parameters(effect);
  17222. _this._linkTextures(effect);
  17223. };
  17224. }
  17225. };
  17226. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17227. for (var renderPassName in this._renderPasses) {
  17228. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17229. }
  17230. for (var renderEffectName in this._renderEffectAsPasses) {
  17231. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17232. }
  17233. };
  17234. return PostProcessRenderEffect;
  17235. })();
  17236. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17237. })(BABYLON || (BABYLON = {}));
  17238. var BABYLON;
  17239. (function (BABYLON) {
  17240. var PostProcessRenderPipeline = (function () {
  17241. function PostProcessRenderPipeline(engine, name) {
  17242. this._engine = engine;
  17243. this._name = name;
  17244. this._renderEffects = [];
  17245. this._renderEffectsForIsolatedPass = [];
  17246. this._cameras = [];
  17247. }
  17248. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17249. this._renderEffects[renderEffect._name] = renderEffect;
  17250. };
  17251. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17252. var renderEffects = this._renderEffects[renderEffectName];
  17253. if (!renderEffects) {
  17254. return;
  17255. }
  17256. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17257. };
  17258. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17259. var renderEffects = this._renderEffects[renderEffectName];
  17260. if (!renderEffects) {
  17261. return;
  17262. }
  17263. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17264. };
  17265. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17266. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17267. var indicesToDelete = [];
  17268. for (var i = 0; i < _cam.length; i++) {
  17269. var camera = _cam[i];
  17270. var cameraName = camera.name;
  17271. if (this._cameras.indexOf(camera) === -1) {
  17272. this._cameras[cameraName] = camera;
  17273. } else if (unique) {
  17274. indicesToDelete.push(i);
  17275. }
  17276. }
  17277. for (var i = 0; i < indicesToDelete.length; i++) {
  17278. cameras.splice(indicesToDelete[i], 1);
  17279. }
  17280. for (var renderEffectName in this._renderEffects) {
  17281. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17282. }
  17283. };
  17284. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17285. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17286. for (var renderEffectName in this._renderEffects) {
  17287. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17288. }
  17289. for (var i = 0; i < _cam.length; i++) {
  17290. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17291. }
  17292. };
  17293. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17294. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17295. var pass = null;
  17296. for (var renderEffectName in this._renderEffects) {
  17297. pass = this._renderEffects[renderEffectName].getPass(passName);
  17298. if (pass != null) {
  17299. break;
  17300. }
  17301. }
  17302. if (pass === null) {
  17303. return;
  17304. }
  17305. for (var renderEffectName in this._renderEffects) {
  17306. this._renderEffects[renderEffectName]._disable(_cam);
  17307. }
  17308. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17309. for (var i = 0; i < _cam.length; i++) {
  17310. var camera = _cam[i];
  17311. var cameraName = camera.name;
  17312. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17313. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17314. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17315. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17316. }
  17317. };
  17318. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17319. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17320. for (var i = 0; i < _cam.length; i++) {
  17321. var camera = _cam[i];
  17322. var cameraName = camera.name;
  17323. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17324. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17325. }
  17326. for (var renderEffectName in this._renderEffects) {
  17327. this._renderEffects[renderEffectName]._enable(_cam);
  17328. }
  17329. };
  17330. PostProcessRenderPipeline.prototype._update = function () {
  17331. for (var renderEffectName in this._renderEffects) {
  17332. this._renderEffects[renderEffectName]._update();
  17333. }
  17334. for (var i = 0; i < this._cameras.length; i++) {
  17335. var cameraName = this._cameras[i].name;
  17336. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17337. this._renderEffectsForIsolatedPass[cameraName]._update();
  17338. }
  17339. }
  17340. };
  17341. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17342. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17343. return PostProcessRenderPipeline;
  17344. })();
  17345. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17346. })(BABYLON || (BABYLON = {}));
  17347. var BABYLON;
  17348. (function (BABYLON) {
  17349. var PostProcessRenderPipelineManager = (function () {
  17350. function PostProcessRenderPipelineManager() {
  17351. this._renderPipelines = [];
  17352. }
  17353. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17354. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17355. };
  17356. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17357. var renderPipeline = this._renderPipelines[renderPipelineName];
  17358. if (!renderPipeline) {
  17359. return;
  17360. }
  17361. renderPipeline.attachCameras(cameras, unique);
  17362. };
  17363. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17364. var renderPipeline = this._renderPipelines[renderPipelineName];
  17365. if (!renderPipeline) {
  17366. return;
  17367. }
  17368. renderPipeline.detachCameras(cameras);
  17369. };
  17370. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17371. var renderPipeline = this._renderPipelines[renderPipelineName];
  17372. if (!renderPipeline) {
  17373. return;
  17374. }
  17375. renderPipeline.enableEffect(renderEffectName, cameras);
  17376. };
  17377. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17378. var renderPipeline = this._renderPipelines[renderPipelineName];
  17379. if (!renderPipeline) {
  17380. return;
  17381. }
  17382. renderPipeline.disableEffect(renderEffectName, cameras);
  17383. };
  17384. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17385. var renderPipeline = this._renderPipelines[renderPipelineName];
  17386. if (!renderPipeline) {
  17387. return;
  17388. }
  17389. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17390. };
  17391. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17392. var renderPipeline = this._renderPipelines[renderPipelineName];
  17393. if (!renderPipeline) {
  17394. return;
  17395. }
  17396. renderPipeline.disableDisplayOnlyPass(cameras);
  17397. };
  17398. PostProcessRenderPipelineManager.prototype.update = function () {
  17399. for (var renderPipelineName in this._renderPipelines) {
  17400. this._renderPipelines[renderPipelineName]._update();
  17401. }
  17402. };
  17403. return PostProcessRenderPipelineManager;
  17404. })();
  17405. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17406. })(BABYLON || (BABYLON = {}));
  17407. var __extends = this.__extends || function (d, b) {
  17408. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17409. function __() { this.constructor = d; }
  17410. __.prototype = b.prototype;
  17411. d.prototype = new __();
  17412. };
  17413. var BABYLON;
  17414. (function (BABYLON) {
  17415. var DisplayPassPostProcess = (function (_super) {
  17416. __extends(DisplayPassPostProcess, _super);
  17417. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17418. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17419. }
  17420. return DisplayPassPostProcess;
  17421. })(BABYLON.PostProcess);
  17422. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17423. })(BABYLON || (BABYLON = {}));
  17424. var BABYLON;
  17425. (function (BABYLON) {
  17426. var BoundingBoxRenderer = (function () {
  17427. function BoundingBoxRenderer(scene) {
  17428. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17429. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17430. this.showBackLines = true;
  17431. this.renderList = new BABYLON.SmartArray(32);
  17432. this._scene = scene;
  17433. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17434. attributes: ["position"],
  17435. uniforms: ["worldViewProjection", "color"]
  17436. });
  17437. var engine = this._scene.getEngine();
  17438. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17439. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17440. 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]);
  17441. }
  17442. BoundingBoxRenderer.prototype.reset = function () {
  17443. this.renderList.reset();
  17444. };
  17445. BoundingBoxRenderer.prototype.render = function () {
  17446. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17447. return;
  17448. }
  17449. var engine = this._scene.getEngine();
  17450. engine.setDepthWrite(false);
  17451. this._colorShader._preBind();
  17452. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17453. var boundingBox = this.renderList.data[boundingBoxIndex];
  17454. var min = boundingBox.minimum;
  17455. var max = boundingBox.maximum;
  17456. var diff = max.subtract(min);
  17457. var median = min.add(diff.scale(0.5));
  17458. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17459. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17460. if (this.showBackLines) {
  17461. engine.setDepthFunctionToGreaterOrEqual();
  17462. this._colorShader.setColor4("color", this.backColor.toColor4());
  17463. this._colorShader.bind(worldMatrix);
  17464. engine.draw(false, 0, 24);
  17465. }
  17466. engine.setDepthFunctionToLess();
  17467. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17468. this._colorShader.bind(worldMatrix);
  17469. engine.draw(false, 0, 24);
  17470. }
  17471. this._colorShader.unbind();
  17472. engine.setDepthFunctionToLessOrEqual();
  17473. engine.setDepthWrite(true);
  17474. };
  17475. BoundingBoxRenderer.prototype.dispose = function () {
  17476. this._colorShader.dispose();
  17477. this._vb.dispose();
  17478. this._scene.getEngine()._releaseBuffer(this._ib);
  17479. };
  17480. return BoundingBoxRenderer;
  17481. })();
  17482. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17483. })(BABYLON || (BABYLON = {}));
  17484. /**
  17485. * Based on jsTGALoader - Javascript loader for TGA file
  17486. * By Vincent Thibault
  17487. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17488. */
  17489. var BABYLON;
  17490. (function (BABYLON) {
  17491. (function (Internals) {
  17492. var TGATools = (function () {
  17493. function TGATools() {
  17494. }
  17495. TGATools.GetTGAHeader = function (data) {
  17496. var offset = 0;
  17497. var header = {
  17498. id_length: data[offset++],
  17499. colormap_type: data[offset++],
  17500. image_type: data[offset++],
  17501. colormap_index: data[offset++] | data[offset++] << 8,
  17502. colormap_length: data[offset++] | data[offset++] << 8,
  17503. colormap_size: data[offset++],
  17504. origin: [
  17505. data[offset++] | data[offset++] << 8,
  17506. data[offset++] | data[offset++] << 8
  17507. ],
  17508. width: data[offset++] | data[offset++] << 8,
  17509. height: data[offset++] | data[offset++] << 8,
  17510. pixel_size: data[offset++],
  17511. flags: data[offset++]
  17512. };
  17513. return header;
  17514. };
  17515. TGATools.UploadContent = function (gl, data) {
  17516. if (data.length < 19) {
  17517. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17518. return;
  17519. }
  17520. var offset = 18;
  17521. var header = TGATools.GetTGAHeader(data);
  17522. if (header.id_length + offset > data.length) {
  17523. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17524. return;
  17525. }
  17526. offset += header.id_length;
  17527. var use_rle = false;
  17528. var use_pal = false;
  17529. var use_rgb = false;
  17530. var use_grey = false;
  17531. switch (header.image_type) {
  17532. case TGATools._TYPE_RLE_INDEXED:
  17533. use_rle = true;
  17534. case TGATools._TYPE_INDEXED:
  17535. use_pal = true;
  17536. break;
  17537. case TGATools._TYPE_RLE_RGB:
  17538. use_rle = true;
  17539. case TGATools._TYPE_RGB:
  17540. use_rgb = true;
  17541. break;
  17542. case TGATools._TYPE_RLE_GREY:
  17543. use_rle = true;
  17544. case TGATools._TYPE_GREY:
  17545. use_grey = true;
  17546. break;
  17547. }
  17548. var pixel_data;
  17549. var numAlphaBits = header.flags & 0xf;
  17550. var pixel_size = header.pixel_size >> 3;
  17551. var pixel_total = header.width * header.height * pixel_size;
  17552. var palettes;
  17553. if (use_pal) {
  17554. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17555. }
  17556. if (use_rle) {
  17557. pixel_data = new Uint8Array(pixel_total);
  17558. var c, count, i;
  17559. var localOffset = 0;
  17560. var pixels = new Uint8Array(pixel_size);
  17561. while (offset < pixel_total && localOffset < pixel_total) {
  17562. c = data[offset++];
  17563. count = (c & 0x7f) + 1;
  17564. if (c & 0x80) {
  17565. for (i = 0; i < pixel_size; ++i) {
  17566. pixels[i] = data[offset++];
  17567. }
  17568. for (i = 0; i < count; ++i) {
  17569. pixel_data.set(pixels, localOffset + i * pixel_size);
  17570. }
  17571. localOffset += pixel_size * count;
  17572. } else {
  17573. count *= pixel_size;
  17574. for (i = 0; i < count; ++i) {
  17575. pixel_data[localOffset + i] = data[offset++];
  17576. }
  17577. localOffset += count;
  17578. }
  17579. }
  17580. } else {
  17581. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17582. }
  17583. var x_start, y_start, x_step, y_step, y_end, x_end;
  17584. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17585. default:
  17586. case TGATools._ORIGIN_UL:
  17587. x_start = 0;
  17588. x_step = 1;
  17589. x_end = header.width;
  17590. y_start = 0;
  17591. y_step = 1;
  17592. y_end = header.height;
  17593. break;
  17594. case TGATools._ORIGIN_BL:
  17595. x_start = 0;
  17596. x_step = 1;
  17597. x_end = header.width;
  17598. y_start = header.height - 1;
  17599. y_step = -1;
  17600. y_end = -1;
  17601. break;
  17602. case TGATools._ORIGIN_UR:
  17603. x_start = header.width - 1;
  17604. x_step = -1;
  17605. x_end = -1;
  17606. y_start = 0;
  17607. y_step = 1;
  17608. y_end = header.height;
  17609. break;
  17610. case TGATools._ORIGIN_BR:
  17611. x_start = header.width - 1;
  17612. x_step = -1;
  17613. x_end = -1;
  17614. y_start = header.height - 1;
  17615. y_step = -1;
  17616. y_end = -1;
  17617. break;
  17618. }
  17619. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17620. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17621. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17622. };
  17623. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17624. var image = pixel_data, colormap = palettes;
  17625. var width = header.width, height = header.height;
  17626. var color, i = 0, x, y;
  17627. var imageData = new Uint8Array(width * height * 4);
  17628. for (y = y_start; y !== y_end; y += y_step) {
  17629. for (x = x_start; x !== x_end; x += x_step, i++) {
  17630. color = image[i];
  17631. imageData[(x + width * y) * 4 + 3] = 255;
  17632. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17633. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17634. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17635. }
  17636. }
  17637. return imageData;
  17638. };
  17639. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17640. var image = pixel_data;
  17641. var width = header.width, height = header.height;
  17642. var color, i = 0, x, y;
  17643. var imageData = new Uint8Array(width * height * 4);
  17644. for (y = y_start; y !== y_end; y += y_step) {
  17645. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17646. color = image[i + 0] + (image[i + 1] << 8);
  17647. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17648. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17649. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17650. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17651. }
  17652. }
  17653. return imageData;
  17654. };
  17655. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17656. var image = pixel_data;
  17657. var width = header.width, height = header.height;
  17658. var i = 0, x, y;
  17659. var imageData = new Uint8Array(width * height * 4);
  17660. for (y = y_start; y !== y_end; y += y_step) {
  17661. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17662. imageData[(x + width * y) * 4 + 3] = 255;
  17663. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17664. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17665. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17666. }
  17667. }
  17668. return imageData;
  17669. };
  17670. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17671. var image = pixel_data;
  17672. var width = header.width, height = header.height;
  17673. var i = 0, x, y;
  17674. var imageData = new Uint8Array(width * height * 4);
  17675. for (y = y_start; y !== y_end; y += y_step) {
  17676. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17677. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17678. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17679. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17680. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17681. }
  17682. }
  17683. return imageData;
  17684. };
  17685. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17686. var image = pixel_data;
  17687. var width = header.width, height = header.height;
  17688. var color, i = 0, x, y;
  17689. var imageData = new Uint8Array(width * height * 4);
  17690. for (y = y_start; y !== y_end; y += y_step) {
  17691. for (x = x_start; x !== x_end; x += x_step, i++) {
  17692. color = image[i];
  17693. imageData[(x + width * y) * 4 + 0] = color;
  17694. imageData[(x + width * y) * 4 + 1] = color;
  17695. imageData[(x + width * y) * 4 + 2] = color;
  17696. imageData[(x + width * y) * 4 + 3] = 255;
  17697. }
  17698. }
  17699. return imageData;
  17700. };
  17701. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17702. var image = pixel_data;
  17703. var width = header.width, height = header.height;
  17704. var i = 0, x, y;
  17705. var imageData = new Uint8Array(width * height * 4);
  17706. for (y = y_start; y !== y_end; y += y_step) {
  17707. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17708. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17709. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17710. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17711. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17712. }
  17713. }
  17714. return imageData;
  17715. };
  17716. TGATools._TYPE_NO_DATA = 0;
  17717. TGATools._TYPE_INDEXED = 1;
  17718. TGATools._TYPE_RGB = 2;
  17719. TGATools._TYPE_GREY = 3;
  17720. TGATools._TYPE_RLE_INDEXED = 9;
  17721. TGATools._TYPE_RLE_RGB = 10;
  17722. TGATools._TYPE_RLE_GREY = 11;
  17723. TGATools._ORIGIN_MASK = 0x30;
  17724. TGATools._ORIGIN_SHIFT = 0x04;
  17725. TGATools._ORIGIN_BL = 0x00;
  17726. TGATools._ORIGIN_BR = 0x01;
  17727. TGATools._ORIGIN_UL = 0x02;
  17728. TGATools._ORIGIN_UR = 0x03;
  17729. return TGATools;
  17730. })();
  17731. Internals.TGATools = TGATools;
  17732. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17733. var Internals = BABYLON.Internals;
  17734. })(BABYLON || (BABYLON = {}));
  17735. var BABYLON;
  17736. (function (BABYLON) {
  17737. (function (Internals) {
  17738. var DDS_MAGIC = 0x20534444;
  17739. 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;
  17740. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17741. 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;
  17742. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17743. function FourCCToInt32(value) {
  17744. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17745. }
  17746. function Int32ToFourCC(value) {
  17747. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17748. }
  17749. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17750. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17751. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17752. var headerLengthInt = 31;
  17753. var off_magic = 0;
  17754. var off_size = 1;
  17755. var off_flags = 2;
  17756. var off_height = 3;
  17757. var off_width = 4;
  17758. var off_mipmapCount = 7;
  17759. var off_pfFlags = 20;
  17760. var off_pfFourCC = 21;
  17761. var off_RGBbpp = 22;
  17762. var off_RMask = 23;
  17763. var off_GMask = 24;
  17764. var off_BMask = 25;
  17765. var off_AMask = 26;
  17766. var off_caps1 = 27;
  17767. var off_caps2 = 28;
  17768. ;
  17769. var DDSTools = (function () {
  17770. function DDSTools() {
  17771. }
  17772. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17773. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17774. var mipmapCount = 1;
  17775. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17776. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17777. }
  17778. return {
  17779. width: header[off_width],
  17780. height: header[off_height],
  17781. mipmapCount: mipmapCount,
  17782. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17783. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17784. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17785. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17786. };
  17787. };
  17788. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17789. var byteArray = new Uint8Array(dataLength);
  17790. var srcData = new Uint8Array(arrayBuffer);
  17791. var index = 0;
  17792. for (var y = height - 1; y >= 0; y--) {
  17793. for (var x = 0; x < width; x++) {
  17794. var srcPos = dataOffset + (x + y * width) * 4;
  17795. byteArray[index + 2] = srcData[srcPos];
  17796. byteArray[index + 1] = srcData[srcPos + 1];
  17797. byteArray[index] = srcData[srcPos + 2];
  17798. byteArray[index + 3] = srcData[srcPos + 3];
  17799. index += 4;
  17800. }
  17801. }
  17802. return byteArray;
  17803. };
  17804. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17805. var byteArray = new Uint8Array(dataLength);
  17806. var srcData = new Uint8Array(arrayBuffer);
  17807. var index = 0;
  17808. for (var y = height - 1; y >= 0; y--) {
  17809. for (var x = 0; x < width; x++) {
  17810. var srcPos = dataOffset + (x + y * width) * 3;
  17811. byteArray[index + 2] = srcData[srcPos];
  17812. byteArray[index + 1] = srcData[srcPos + 1];
  17813. byteArray[index] = srcData[srcPos + 2];
  17814. index += 3;
  17815. }
  17816. }
  17817. return byteArray;
  17818. };
  17819. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17820. var byteArray = new Uint8Array(dataLength);
  17821. var srcData = new Uint8Array(arrayBuffer);
  17822. var index = 0;
  17823. for (var y = height - 1; y >= 0; y--) {
  17824. for (var x = 0; x < width; x++) {
  17825. var srcPos = dataOffset + (x + y * width);
  17826. byteArray[index] = srcData[srcPos];
  17827. index++;
  17828. }
  17829. }
  17830. return byteArray;
  17831. };
  17832. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17833. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17834. if (header[off_magic] != DDS_MAGIC) {
  17835. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17836. return;
  17837. }
  17838. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17839. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17840. return;
  17841. }
  17842. if (info.isFourCC) {
  17843. fourCC = header[off_pfFourCC];
  17844. switch (fourCC) {
  17845. case FOURCC_DXT1:
  17846. blockBytes = 8;
  17847. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17848. break;
  17849. case FOURCC_DXT3:
  17850. blockBytes = 16;
  17851. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17852. break;
  17853. case FOURCC_DXT5:
  17854. blockBytes = 16;
  17855. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17856. break;
  17857. default:
  17858. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17859. return;
  17860. }
  17861. }
  17862. mipmapCount = 1;
  17863. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17864. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17865. }
  17866. var bpp = header[off_RGBbpp];
  17867. for (var face = 0; face < faces; face++) {
  17868. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17869. width = header[off_width];
  17870. height = header[off_height];
  17871. dataOffset = header[off_size] + 4;
  17872. for (i = 0; i < mipmapCount; ++i) {
  17873. if (info.isRGB) {
  17874. if (bpp == 24) {
  17875. dataLength = width * height * 3;
  17876. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17877. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17878. } else {
  17879. dataLength = width * height * 4;
  17880. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17881. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17882. }
  17883. } else if (info.isLuminance) {
  17884. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17885. var unpaddedRowSize = width;
  17886. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17887. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17888. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17889. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17890. } else {
  17891. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17892. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17893. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17894. }
  17895. dataOffset += dataLength;
  17896. width *= 0.5;
  17897. height *= 0.5;
  17898. width = Math.max(1.0, width);
  17899. height = Math.max(1.0, height);
  17900. }
  17901. }
  17902. };
  17903. return DDSTools;
  17904. })();
  17905. Internals.DDSTools = DDSTools;
  17906. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17907. var Internals = BABYLON.Internals;
  17908. })(BABYLON || (BABYLON = {}));
  17909. var BABYLON;
  17910. (function (BABYLON) {
  17911. var SmartArray = (function () {
  17912. function SmartArray(capacity) {
  17913. this.length = 0;
  17914. this._duplicateId = 0;
  17915. this.data = new Array(capacity);
  17916. this._id = SmartArray._GlobalId++;
  17917. }
  17918. SmartArray.prototype.push = function (value) {
  17919. this.data[this.length++] = value;
  17920. if (this.length > this.data.length) {
  17921. this.data.length *= 2;
  17922. }
  17923. if (!value.__smartArrayFlags) {
  17924. value.__smartArrayFlags = {};
  17925. }
  17926. value.__smartArrayFlags[this._id] = this._duplicateId;
  17927. };
  17928. SmartArray.prototype.pushNoDuplicate = function (value) {
  17929. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17930. return;
  17931. }
  17932. this.push(value);
  17933. };
  17934. SmartArray.prototype.sort = function (compareFn) {
  17935. this.data.sort(compareFn);
  17936. };
  17937. SmartArray.prototype.reset = function () {
  17938. this.length = 0;
  17939. this._duplicateId++;
  17940. };
  17941. SmartArray.prototype.concat = function (array) {
  17942. if (array.length === 0) {
  17943. return;
  17944. }
  17945. if (this.length + array.length > this.data.length) {
  17946. this.data.length = (this.length + array.length) * 2;
  17947. }
  17948. for (var index = 0; index < array.length; index++) {
  17949. this.data[this.length++] = (array.data || array)[index];
  17950. }
  17951. };
  17952. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17953. if (array.length === 0) {
  17954. return;
  17955. }
  17956. if (this.length + array.length > this.data.length) {
  17957. this.data.length = (this.length + array.length) * 2;
  17958. }
  17959. for (var index = 0; index < array.length; index++) {
  17960. var item = (array.data || array)[index];
  17961. this.pushNoDuplicate(item);
  17962. }
  17963. };
  17964. SmartArray.prototype.indexOf = function (value) {
  17965. var position = this.data.indexOf(value);
  17966. if (position >= this.length) {
  17967. return -1;
  17968. }
  17969. return position;
  17970. };
  17971. SmartArray._GlobalId = 0;
  17972. return SmartArray;
  17973. })();
  17974. BABYLON.SmartArray = SmartArray;
  17975. })(BABYLON || (BABYLON = {}));
  17976. var BABYLON;
  17977. (function (BABYLON) {
  17978. var CannonJSPlugin = (function () {
  17979. function CannonJSPlugin() {
  17980. this._registeredMeshes = [];
  17981. this._physicsMaterials = [];
  17982. this.updateBodyPosition = function (mesh) {
  17983. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17984. var registeredMesh = this._registeredMeshes[index];
  17985. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17986. var body = registeredMesh.body.body;
  17987. var center = mesh.getBoundingInfo().boundingBox.center;
  17988. body.position.set(center.x, center.z, center.y);
  17989. body.quaternion.x = mesh.rotationQuaternion.x;
  17990. body.quaternion.z = mesh.rotationQuaternion.y;
  17991. body.quaternion.y = mesh.rotationQuaternion.z;
  17992. body.quaternion.w = -mesh.rotationQuaternion.w;
  17993. return;
  17994. }
  17995. }
  17996. };
  17997. }
  17998. CannonJSPlugin.prototype.initialize = function (iterations) {
  17999. if (typeof iterations === "undefined") { iterations = 10; }
  18000. this._world = new CANNON.World();
  18001. this._world.broadphase = new CANNON.NaiveBroadphase();
  18002. this._world.solver.iterations = iterations;
  18003. };
  18004. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18005. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18006. };
  18007. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18008. this._world.step(delta);
  18009. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18010. var registeredMesh = this._registeredMeshes[index];
  18011. if (registeredMesh.isChild) {
  18012. continue;
  18013. }
  18014. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18015. var deltaPos = registeredMesh.delta;
  18016. if (deltaPos) {
  18017. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18018. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18019. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18020. } else {
  18021. registeredMesh.mesh.position.x = bodyX;
  18022. registeredMesh.mesh.position.y = bodyZ;
  18023. registeredMesh.mesh.position.z = bodyY;
  18024. }
  18025. if (!registeredMesh.mesh.rotationQuaternion) {
  18026. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18027. }
  18028. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18029. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18030. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18031. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18032. }
  18033. };
  18034. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18035. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18036. };
  18037. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18038. this.unregisterMesh(mesh);
  18039. mesh.computeWorldMatrix(true);
  18040. switch (impostor) {
  18041. case BABYLON.PhysicsEngine.SphereImpostor:
  18042. var bbox = mesh.getBoundingInfo().boundingBox;
  18043. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18044. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18045. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18046. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18047. case BABYLON.PhysicsEngine.BoxImpostor:
  18048. bbox = mesh.getBoundingInfo().boundingBox;
  18049. var min = bbox.minimumWorld;
  18050. var max = bbox.maximumWorld;
  18051. var box = max.subtract(min).scale(0.5);
  18052. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18053. case BABYLON.PhysicsEngine.PlaneImpostor:
  18054. return this._createPlane(mesh, options);
  18055. case BABYLON.PhysicsEngine.MeshImpostor:
  18056. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18057. var rawFaces = mesh.getIndices();
  18058. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18059. }
  18060. return null;
  18061. };
  18062. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18063. var shape = new CANNON.Sphere(radius);
  18064. if (!options) {
  18065. return shape;
  18066. }
  18067. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18068. };
  18069. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18070. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18071. if (!options) {
  18072. return shape;
  18073. }
  18074. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18075. };
  18076. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18077. var shape = new CANNON.Plane();
  18078. if (!options) {
  18079. return shape;
  18080. }
  18081. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18082. };
  18083. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18084. var verts = [], faces = [];
  18085. mesh.computeWorldMatrix(true);
  18086. for (var i = 0; i < rawVerts.length; i += 3) {
  18087. var transformed = BABYLON.Vector3.Zero();
  18088. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18089. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18090. }
  18091. for (var j = 0; j < rawFaces.length; j += 3) {
  18092. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18093. }
  18094. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18095. if (!options) {
  18096. return shape;
  18097. }
  18098. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18099. };
  18100. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18101. var index;
  18102. var mat;
  18103. for (index = 0; index < this._physicsMaterials.length; index++) {
  18104. mat = this._physicsMaterials[index];
  18105. if (mat.friction === friction && mat.restitution === restitution) {
  18106. return mat;
  18107. }
  18108. }
  18109. var currentMat = new CANNON.Material();
  18110. currentMat.friction = friction;
  18111. currentMat.restitution = restitution;
  18112. this._physicsMaterials.push(currentMat);
  18113. for (index = 0; index < this._physicsMaterials.length; index++) {
  18114. mat = this._physicsMaterials[index];
  18115. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18116. contactMaterial.contactEquationStiffness = 1e10;
  18117. contactMaterial.contactEquationRegularizationTime = 10;
  18118. this._world.addContactMaterial(contactMaterial);
  18119. }
  18120. return currentMat;
  18121. };
  18122. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18123. var initialRotation = null;
  18124. if (mesh.rotationQuaternion) {
  18125. initialRotation = mesh.rotationQuaternion.clone();
  18126. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18127. }
  18128. var bbox = mesh.getBoundingInfo().boundingBox;
  18129. var deltaPosition = mesh.position.subtract(bbox.center);
  18130. var material = this._addMaterial(friction, restitution);
  18131. var body = new CANNON.RigidBody(mass, shape, material);
  18132. if (initialRotation) {
  18133. body.quaternion.x = initialRotation.x;
  18134. body.quaternion.z = initialRotation.y;
  18135. body.quaternion.y = initialRotation.z;
  18136. body.quaternion.w = -initialRotation.w;
  18137. }
  18138. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18139. this._world.add(body);
  18140. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18141. return body;
  18142. };
  18143. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18144. var compoundShape = new CANNON.Compound();
  18145. for (var index = 0; index < parts.length; index++) {
  18146. var mesh = parts[index].mesh;
  18147. var shape = this.registerMesh(mesh, parts[index].impostor);
  18148. if (index == 0) {
  18149. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18150. } else {
  18151. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18152. }
  18153. }
  18154. var initialMesh = parts[0].mesh;
  18155. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18156. body.parts = parts;
  18157. return body;
  18158. };
  18159. CannonJSPlugin.prototype._unbindBody = function (body) {
  18160. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18161. var registeredMesh = this._registeredMeshes[index];
  18162. if (registeredMesh.body === body) {
  18163. registeredMesh.body = null;
  18164. registeredMesh.delta = 0;
  18165. }
  18166. }
  18167. };
  18168. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18169. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18170. var registeredMesh = this._registeredMeshes[index];
  18171. if (registeredMesh.mesh === mesh) {
  18172. if (registeredMesh.body) {
  18173. this._world.remove(registeredMesh.body);
  18174. this._unbindBody(registeredMesh.body);
  18175. }
  18176. this._registeredMeshes.splice(index, 1);
  18177. return;
  18178. }
  18179. }
  18180. };
  18181. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18182. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18183. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18184. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18185. var registeredMesh = this._registeredMeshes[index];
  18186. if (registeredMesh.mesh === mesh) {
  18187. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18188. return;
  18189. }
  18190. }
  18191. };
  18192. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18193. var body1 = null, body2 = null;
  18194. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18195. var registeredMesh = this._registeredMeshes[index];
  18196. if (registeredMesh.mesh === mesh1) {
  18197. body1 = registeredMesh.body;
  18198. } else if (registeredMesh.mesh === mesh2) {
  18199. body2 = registeredMesh.body;
  18200. }
  18201. }
  18202. if (!body1 || !body2) {
  18203. return false;
  18204. }
  18205. 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));
  18206. this._world.addConstraint(constraint);
  18207. return true;
  18208. };
  18209. CannonJSPlugin.prototype.dispose = function () {
  18210. while (this._registeredMeshes.length) {
  18211. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18212. }
  18213. };
  18214. CannonJSPlugin.prototype.isSupported = function () {
  18215. return window.CANNON !== undefined;
  18216. };
  18217. return CannonJSPlugin;
  18218. })();
  18219. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18220. })(BABYLON || (BABYLON = {}));
  18221. var __extends = this.__extends || function (d, b) {
  18222. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18223. function __() { this.constructor = d; }
  18224. __.prototype = b.prototype;
  18225. d.prototype = new __();
  18226. };
  18227. var BABYLON;
  18228. (function (BABYLON) {
  18229. var Condition = (function () {
  18230. function Condition(actionManager) {
  18231. this._actionManager = actionManager;
  18232. }
  18233. Condition.prototype.isValid = function () {
  18234. return true;
  18235. };
  18236. Condition.prototype._getProperty = function (propertyPath) {
  18237. return this._actionManager._getProperty(propertyPath);
  18238. };
  18239. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18240. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18241. };
  18242. return Condition;
  18243. })();
  18244. BABYLON.Condition = Condition;
  18245. var ValueCondition = (function (_super) {
  18246. __extends(ValueCondition, _super);
  18247. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18248. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18249. _super.call(this, actionManager);
  18250. this.propertyPath = propertyPath;
  18251. this.value = value;
  18252. this.operator = operator;
  18253. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18254. this._property = this._getProperty(this.propertyPath);
  18255. }
  18256. Object.defineProperty(ValueCondition, "IsEqual", {
  18257. get: function () {
  18258. return ValueCondition._IsEqual;
  18259. },
  18260. enumerable: true,
  18261. configurable: true
  18262. });
  18263. Object.defineProperty(ValueCondition, "IsDifferent", {
  18264. get: function () {
  18265. return ValueCondition._IsDifferent;
  18266. },
  18267. enumerable: true,
  18268. configurable: true
  18269. });
  18270. Object.defineProperty(ValueCondition, "IsGreater", {
  18271. get: function () {
  18272. return ValueCondition._IsGreater;
  18273. },
  18274. enumerable: true,
  18275. configurable: true
  18276. });
  18277. Object.defineProperty(ValueCondition, "IsLesser", {
  18278. get: function () {
  18279. return ValueCondition._IsLesser;
  18280. },
  18281. enumerable: true,
  18282. configurable: true
  18283. });
  18284. ValueCondition.prototype.isValid = function () {
  18285. switch (this.operator) {
  18286. case ValueCondition.IsGreater:
  18287. return this._target[this._property] > this.value;
  18288. case ValueCondition.IsLesser:
  18289. return this._target[this._property] < this.value;
  18290. case ValueCondition.IsEqual:
  18291. case ValueCondition.IsDifferent:
  18292. var check;
  18293. if (this.value.equals) {
  18294. check = this.value.equals(this._target[this._property]);
  18295. } else {
  18296. check = this.value === this._target[this._property];
  18297. }
  18298. return this.operator === ValueCondition.IsEqual ? check : !check;
  18299. }
  18300. return false;
  18301. };
  18302. ValueCondition._IsEqual = 0;
  18303. ValueCondition._IsDifferent = 1;
  18304. ValueCondition._IsGreater = 2;
  18305. ValueCondition._IsLesser = 3;
  18306. return ValueCondition;
  18307. })(Condition);
  18308. BABYLON.ValueCondition = ValueCondition;
  18309. var PredicateCondition = (function (_super) {
  18310. __extends(PredicateCondition, _super);
  18311. function PredicateCondition(actionManager, predicate) {
  18312. _super.call(this, actionManager);
  18313. this.predicate = predicate;
  18314. }
  18315. PredicateCondition.prototype.isValid = function () {
  18316. return this.predicate();
  18317. };
  18318. return PredicateCondition;
  18319. })(Condition);
  18320. BABYLON.PredicateCondition = PredicateCondition;
  18321. var StateCondition = (function (_super) {
  18322. __extends(StateCondition, _super);
  18323. function StateCondition(actionManager, target, value) {
  18324. _super.call(this, actionManager);
  18325. this.value = value;
  18326. this._target = target;
  18327. }
  18328. StateCondition.prototype.isValid = function () {
  18329. return this._target.state === this.value;
  18330. };
  18331. return StateCondition;
  18332. })(Condition);
  18333. BABYLON.StateCondition = StateCondition;
  18334. })(BABYLON || (BABYLON = {}));
  18335. var BABYLON;
  18336. (function (BABYLON) {
  18337. var Action = (function () {
  18338. function Action(triggerOptions, condition) {
  18339. this.triggerOptions = triggerOptions;
  18340. if (triggerOptions.parameter) {
  18341. this.trigger = triggerOptions.trigger;
  18342. this._triggerParameter = triggerOptions.parameter;
  18343. } else {
  18344. this.trigger = triggerOptions;
  18345. }
  18346. this._nextActiveAction = this;
  18347. this._condition = condition;
  18348. }
  18349. Action.prototype._prepare = function () {
  18350. };
  18351. Action.prototype.getTriggerParameter = function () {
  18352. return this._triggerParameter;
  18353. };
  18354. Action.prototype._executeCurrent = function (evt) {
  18355. if (this._condition) {
  18356. var currentRenderId = this._actionManager.getScene().getRenderId();
  18357. if (this._condition._evaluationId === currentRenderId) {
  18358. if (!this._condition._currentResult) {
  18359. return;
  18360. }
  18361. } else {
  18362. this._condition._evaluationId = currentRenderId;
  18363. if (!this._condition.isValid()) {
  18364. this._condition._currentResult = false;
  18365. return;
  18366. }
  18367. this._condition._currentResult = true;
  18368. }
  18369. }
  18370. this._nextActiveAction.execute(evt);
  18371. if (this._nextActiveAction._child) {
  18372. if (!this._nextActiveAction._child._actionManager) {
  18373. this._nextActiveAction._child._actionManager = this._actionManager;
  18374. }
  18375. this._nextActiveAction = this._nextActiveAction._child;
  18376. } else {
  18377. this._nextActiveAction = this;
  18378. }
  18379. };
  18380. Action.prototype.execute = function (evt) {
  18381. };
  18382. Action.prototype.then = function (action) {
  18383. this._child = action;
  18384. action._actionManager = this._actionManager;
  18385. action._prepare();
  18386. return action;
  18387. };
  18388. Action.prototype._getProperty = function (propertyPath) {
  18389. return this._actionManager._getProperty(propertyPath);
  18390. };
  18391. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18392. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18393. };
  18394. return Action;
  18395. })();
  18396. BABYLON.Action = Action;
  18397. })(BABYLON || (BABYLON = {}));
  18398. var BABYLON;
  18399. (function (BABYLON) {
  18400. var ActionEvent = (function () {
  18401. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18402. this.source = source;
  18403. this.pointerX = pointerX;
  18404. this.pointerY = pointerY;
  18405. this.meshUnderPointer = meshUnderPointer;
  18406. this.sourceEvent = sourceEvent;
  18407. }
  18408. ActionEvent.CreateNew = function (source) {
  18409. var scene = source.getScene();
  18410. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18411. };
  18412. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18413. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18414. };
  18415. return ActionEvent;
  18416. })();
  18417. BABYLON.ActionEvent = ActionEvent;
  18418. var ActionManager = (function () {
  18419. function ActionManager(scene) {
  18420. this.actions = new Array();
  18421. this._scene = scene;
  18422. scene._actionManagers.push(this);
  18423. }
  18424. Object.defineProperty(ActionManager, "NothingTrigger", {
  18425. get: function () {
  18426. return ActionManager._NothingTrigger;
  18427. },
  18428. enumerable: true,
  18429. configurable: true
  18430. });
  18431. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18432. get: function () {
  18433. return ActionManager._OnPickTrigger;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18439. get: function () {
  18440. return ActionManager._OnLeftPickTrigger;
  18441. },
  18442. enumerable: true,
  18443. configurable: true
  18444. });
  18445. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18446. get: function () {
  18447. return ActionManager._OnRightPickTrigger;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18453. get: function () {
  18454. return ActionManager._OnCenterPickTrigger;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18460. get: function () {
  18461. return ActionManager._OnPointerOverTrigger;
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18467. get: function () {
  18468. return ActionManager._OnPointerOutTrigger;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18474. get: function () {
  18475. return ActionManager._OnEveryFrameTrigger;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18481. get: function () {
  18482. return ActionManager._OnIntersectionEnterTrigger;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18488. get: function () {
  18489. return ActionManager._OnIntersectionExitTrigger;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18495. get: function () {
  18496. return ActionManager._OnKeyDownTrigger;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18502. get: function () {
  18503. return ActionManager._OnKeyUpTrigger;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. ActionManager.prototype.dispose = function () {
  18509. var index = this._scene._actionManagers.indexOf(this);
  18510. if (index > -1) {
  18511. this._scene._actionManagers.splice(index, 1);
  18512. }
  18513. };
  18514. ActionManager.prototype.getScene = function () {
  18515. return this._scene;
  18516. };
  18517. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18518. for (var index = 0; index < this.actions.length; index++) {
  18519. var action = this.actions[index];
  18520. if (triggers.indexOf(action.trigger) > -1) {
  18521. return true;
  18522. }
  18523. }
  18524. return false;
  18525. };
  18526. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18527. get: function () {
  18528. for (var index = 0; index < this.actions.length; index++) {
  18529. var action = this.actions[index];
  18530. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18531. return true;
  18532. }
  18533. }
  18534. return false;
  18535. },
  18536. enumerable: true,
  18537. configurable: true
  18538. });
  18539. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18540. get: function () {
  18541. for (var index = 0; index < this.actions.length; index++) {
  18542. var action = this.actions[index];
  18543. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18544. return true;
  18545. }
  18546. }
  18547. return false;
  18548. },
  18549. enumerable: true,
  18550. configurable: true
  18551. });
  18552. ActionManager.prototype.registerAction = function (action) {
  18553. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18554. if (this.getScene().actionManager !== this) {
  18555. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18556. return null;
  18557. }
  18558. }
  18559. this.actions.push(action);
  18560. action._actionManager = this;
  18561. action._prepare();
  18562. return action;
  18563. };
  18564. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18565. for (var index = 0; index < this.actions.length; index++) {
  18566. var action = this.actions[index];
  18567. if (action.trigger === trigger) {
  18568. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18569. var parameter = action.getTriggerParameter();
  18570. if (parameter) {
  18571. if (evt.sourceEvent.key !== parameter) {
  18572. continue;
  18573. }
  18574. }
  18575. }
  18576. action._executeCurrent(evt);
  18577. }
  18578. }
  18579. };
  18580. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18581. var properties = propertyPath.split(".");
  18582. for (var index = 0; index < properties.length - 1; index++) {
  18583. target = target[properties[index]];
  18584. }
  18585. return target;
  18586. };
  18587. ActionManager.prototype._getProperty = function (propertyPath) {
  18588. var properties = propertyPath.split(".");
  18589. return properties[properties.length - 1];
  18590. };
  18591. ActionManager._NothingTrigger = 0;
  18592. ActionManager._OnPickTrigger = 1;
  18593. ActionManager._OnLeftPickTrigger = 2;
  18594. ActionManager._OnRightPickTrigger = 3;
  18595. ActionManager._OnCenterPickTrigger = 4;
  18596. ActionManager._OnPointerOverTrigger = 5;
  18597. ActionManager._OnPointerOutTrigger = 6;
  18598. ActionManager._OnEveryFrameTrigger = 7;
  18599. ActionManager._OnIntersectionEnterTrigger = 8;
  18600. ActionManager._OnIntersectionExitTrigger = 9;
  18601. ActionManager._OnKeyDownTrigger = 10;
  18602. ActionManager._OnKeyUpTrigger = 11;
  18603. return ActionManager;
  18604. })();
  18605. BABYLON.ActionManager = ActionManager;
  18606. })(BABYLON || (BABYLON = {}));
  18607. var __extends = this.__extends || function (d, b) {
  18608. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18609. function __() { this.constructor = d; }
  18610. __.prototype = b.prototype;
  18611. d.prototype = new __();
  18612. };
  18613. var BABYLON;
  18614. (function (BABYLON) {
  18615. var InterpolateValueAction = (function (_super) {
  18616. __extends(InterpolateValueAction, _super);
  18617. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18618. if (typeof duration === "undefined") { duration = 1000; }
  18619. _super.call(this, triggerOptions, condition);
  18620. this.propertyPath = propertyPath;
  18621. this.value = value;
  18622. this.duration = duration;
  18623. this.stopOtherAnimations = stopOtherAnimations;
  18624. this._target = target;
  18625. }
  18626. InterpolateValueAction.prototype._prepare = function () {
  18627. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18628. this._property = this._getProperty(this.propertyPath);
  18629. };
  18630. InterpolateValueAction.prototype.execute = function () {
  18631. var scene = this._actionManager.getScene();
  18632. var keys = [
  18633. {
  18634. frame: 0,
  18635. value: this._target[this._property]
  18636. }, {
  18637. frame: 100,
  18638. value: this.value
  18639. }
  18640. ];
  18641. var dataType;
  18642. if (typeof this.value === "number") {
  18643. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18644. } else if (this.value instanceof BABYLON.Color3) {
  18645. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18646. } else if (this.value instanceof BABYLON.Vector3) {
  18647. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18648. } else if (this.value instanceof BABYLON.Matrix) {
  18649. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18650. } else if (this.value instanceof BABYLON.Quaternion) {
  18651. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18652. } else {
  18653. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18654. return;
  18655. }
  18656. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18657. animation.setKeys(keys);
  18658. if (this.stopOtherAnimations) {
  18659. scene.stopAnimation(this._target);
  18660. }
  18661. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18662. };
  18663. return InterpolateValueAction;
  18664. })(BABYLON.Action);
  18665. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18666. })(BABYLON || (BABYLON = {}));
  18667. var __extends = this.__extends || function (d, b) {
  18668. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18669. function __() { this.constructor = d; }
  18670. __.prototype = b.prototype;
  18671. d.prototype = new __();
  18672. };
  18673. var BABYLON;
  18674. (function (BABYLON) {
  18675. var SwitchBooleanAction = (function (_super) {
  18676. __extends(SwitchBooleanAction, _super);
  18677. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18678. _super.call(this, triggerOptions, condition);
  18679. this.propertyPath = propertyPath;
  18680. this._target = target;
  18681. }
  18682. SwitchBooleanAction.prototype._prepare = function () {
  18683. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18684. this._property = this._getProperty(this.propertyPath);
  18685. };
  18686. SwitchBooleanAction.prototype.execute = function () {
  18687. this._target[this._property] = !this._target[this._property];
  18688. };
  18689. return SwitchBooleanAction;
  18690. })(BABYLON.Action);
  18691. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18692. var SetStateAction = (function (_super) {
  18693. __extends(SetStateAction, _super);
  18694. function SetStateAction(triggerOptions, target, value, condition) {
  18695. _super.call(this, triggerOptions, condition);
  18696. this.value = value;
  18697. this._target = target;
  18698. }
  18699. SetStateAction.prototype.execute = function () {
  18700. this._target.state = this.value;
  18701. };
  18702. return SetStateAction;
  18703. })(BABYLON.Action);
  18704. BABYLON.SetStateAction = SetStateAction;
  18705. var SetValueAction = (function (_super) {
  18706. __extends(SetValueAction, _super);
  18707. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18708. _super.call(this, triggerOptions, condition);
  18709. this.propertyPath = propertyPath;
  18710. this.value = value;
  18711. this._target = target;
  18712. }
  18713. SetValueAction.prototype._prepare = function () {
  18714. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18715. this._property = this._getProperty(this.propertyPath);
  18716. };
  18717. SetValueAction.prototype.execute = function () {
  18718. this._target[this._property] = this.value;
  18719. };
  18720. return SetValueAction;
  18721. })(BABYLON.Action);
  18722. BABYLON.SetValueAction = SetValueAction;
  18723. var IncrementValueAction = (function (_super) {
  18724. __extends(IncrementValueAction, _super);
  18725. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18726. _super.call(this, triggerOptions, condition);
  18727. this.propertyPath = propertyPath;
  18728. this.value = value;
  18729. this._target = target;
  18730. }
  18731. IncrementValueAction.prototype._prepare = function () {
  18732. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18733. this._property = this._getProperty(this.propertyPath);
  18734. if (typeof this._target[this._property] !== "number") {
  18735. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18736. }
  18737. };
  18738. IncrementValueAction.prototype.execute = function () {
  18739. this._target[this._property] += this.value;
  18740. };
  18741. return IncrementValueAction;
  18742. })(BABYLON.Action);
  18743. BABYLON.IncrementValueAction = IncrementValueAction;
  18744. var PlayAnimationAction = (function (_super) {
  18745. __extends(PlayAnimationAction, _super);
  18746. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18747. _super.call(this, triggerOptions, condition);
  18748. this.from = from;
  18749. this.to = to;
  18750. this.loop = loop;
  18751. this._target = target;
  18752. }
  18753. PlayAnimationAction.prototype._prepare = function () {
  18754. };
  18755. PlayAnimationAction.prototype.execute = function () {
  18756. var scene = this._actionManager.getScene();
  18757. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18758. };
  18759. return PlayAnimationAction;
  18760. })(BABYLON.Action);
  18761. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18762. var StopAnimationAction = (function (_super) {
  18763. __extends(StopAnimationAction, _super);
  18764. function StopAnimationAction(triggerOptions, target, condition) {
  18765. _super.call(this, triggerOptions, condition);
  18766. this._target = target;
  18767. }
  18768. StopAnimationAction.prototype._prepare = function () {
  18769. };
  18770. StopAnimationAction.prototype.execute = function () {
  18771. var scene = this._actionManager.getScene();
  18772. scene.stopAnimation(this._target);
  18773. };
  18774. return StopAnimationAction;
  18775. })(BABYLON.Action);
  18776. BABYLON.StopAnimationAction = StopAnimationAction;
  18777. var DoNothingAction = (function (_super) {
  18778. __extends(DoNothingAction, _super);
  18779. function DoNothingAction(triggerOptions, condition) {
  18780. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18781. _super.call(this, triggerOptions, condition);
  18782. }
  18783. DoNothingAction.prototype.execute = function () {
  18784. };
  18785. return DoNothingAction;
  18786. })(BABYLON.Action);
  18787. BABYLON.DoNothingAction = DoNothingAction;
  18788. var CombineAction = (function (_super) {
  18789. __extends(CombineAction, _super);
  18790. function CombineAction(triggerOptions, children, condition) {
  18791. _super.call(this, triggerOptions, condition);
  18792. this.children = children;
  18793. }
  18794. CombineAction.prototype._prepare = function () {
  18795. for (var index = 0; index < this.children.length; index++) {
  18796. this.children[index]._actionManager = this._actionManager;
  18797. this.children[index]._prepare();
  18798. }
  18799. };
  18800. CombineAction.prototype.execute = function (evt) {
  18801. for (var index = 0; index < this.children.length; index++) {
  18802. this.children[index].execute(evt);
  18803. }
  18804. };
  18805. return CombineAction;
  18806. })(BABYLON.Action);
  18807. BABYLON.CombineAction = CombineAction;
  18808. var ExecuteCodeAction = (function (_super) {
  18809. __extends(ExecuteCodeAction, _super);
  18810. function ExecuteCodeAction(triggerOptions, func, condition) {
  18811. _super.call(this, triggerOptions, condition);
  18812. this.func = func;
  18813. }
  18814. ExecuteCodeAction.prototype.execute = function (evt) {
  18815. this.func(evt);
  18816. };
  18817. return ExecuteCodeAction;
  18818. })(BABYLON.Action);
  18819. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18820. var SetParentAction = (function (_super) {
  18821. __extends(SetParentAction, _super);
  18822. function SetParentAction(triggerOptions, target, parent, condition) {
  18823. _super.call(this, triggerOptions, condition);
  18824. this._target = target;
  18825. this._parent = parent;
  18826. }
  18827. SetParentAction.prototype._prepare = function () {
  18828. };
  18829. SetParentAction.prototype.execute = function () {
  18830. if (this._target.parent === this._parent) {
  18831. return;
  18832. }
  18833. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18834. invertParentWorldMatrix.invert();
  18835. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18836. this._target.parent = this._parent;
  18837. };
  18838. return SetParentAction;
  18839. })(BABYLON.Action);
  18840. BABYLON.SetParentAction = SetParentAction;
  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 Geometry = (function () {
  18851. function Geometry(id, scene, vertexData, updatable, mesh) {
  18852. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18853. this._totalVertices = 0;
  18854. this._indices = [];
  18855. this.id = id;
  18856. this._engine = scene.getEngine();
  18857. this._meshes = [];
  18858. this._scene = scene;
  18859. if (vertexData) {
  18860. this.setAllVerticesData(vertexData, updatable);
  18861. } else {
  18862. this._totalVertices = 0;
  18863. this._indices = [];
  18864. }
  18865. if (mesh) {
  18866. this.applyToMesh(mesh);
  18867. }
  18868. }
  18869. Geometry.prototype.getScene = function () {
  18870. return this._scene;
  18871. };
  18872. Geometry.prototype.getEngine = function () {
  18873. return this._engine;
  18874. };
  18875. Geometry.prototype.isReady = function () {
  18876. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18877. };
  18878. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18879. vertexData.applyToGeometry(this, updatable);
  18880. };
  18881. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18882. this._vertexBuffers = this._vertexBuffers || {};
  18883. if (this._vertexBuffers[kind]) {
  18884. this._vertexBuffers[kind].dispose();
  18885. }
  18886. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18887. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18888. var stride = this._vertexBuffers[kind].getStrideSize();
  18889. this._totalVertices = data.length / stride;
  18890. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18891. var meshes = this._meshes;
  18892. var numOfMeshes = meshes.length;
  18893. for (var index = 0; index < numOfMeshes; index++) {
  18894. var mesh = meshes[index];
  18895. mesh._resetPointsArrayCache();
  18896. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18897. mesh._createGlobalSubMesh();
  18898. mesh.computeWorldMatrix(true);
  18899. }
  18900. }
  18901. };
  18902. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18903. var vertexBuffer = this.getVertexBuffer(kind);
  18904. if (!vertexBuffer) {
  18905. return;
  18906. }
  18907. vertexBuffer.update(data);
  18908. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18909. var extend;
  18910. if (updateExtends) {
  18911. var stride = vertexBuffer.getStrideSize();
  18912. this._totalVertices = data.length / stride;
  18913. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18914. }
  18915. var meshes = this._meshes;
  18916. var numOfMeshes = meshes.length;
  18917. for (var index = 0; index < numOfMeshes; index++) {
  18918. var mesh = meshes[index];
  18919. mesh._resetPointsArrayCache();
  18920. if (updateExtends) {
  18921. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18922. }
  18923. }
  18924. }
  18925. };
  18926. Geometry.prototype.getTotalVertices = function () {
  18927. if (!this.isReady()) {
  18928. return 0;
  18929. }
  18930. return this._totalVertices;
  18931. };
  18932. Geometry.prototype.getVerticesData = function (kind) {
  18933. var vertexBuffer = this.getVertexBuffer(kind);
  18934. if (!vertexBuffer) {
  18935. return null;
  18936. }
  18937. return vertexBuffer.getData();
  18938. };
  18939. Geometry.prototype.getVertexBuffer = function (kind) {
  18940. if (!this.isReady()) {
  18941. return null;
  18942. }
  18943. return this._vertexBuffers[kind];
  18944. };
  18945. Geometry.prototype.getVertexBuffers = function () {
  18946. if (!this.isReady()) {
  18947. return null;
  18948. }
  18949. return this._vertexBuffers;
  18950. };
  18951. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18952. if (!this._vertexBuffers) {
  18953. if (this._delayInfo) {
  18954. return this._delayInfo.indexOf(kind) !== -1;
  18955. }
  18956. return false;
  18957. }
  18958. return this._vertexBuffers[kind] !== undefined;
  18959. };
  18960. Geometry.prototype.getVerticesDataKinds = function () {
  18961. var result = [];
  18962. if (!this._vertexBuffers && this._delayInfo) {
  18963. for (var kind in this._delayInfo) {
  18964. result.push(kind);
  18965. }
  18966. } else {
  18967. for (kind in this._vertexBuffers) {
  18968. result.push(kind);
  18969. }
  18970. }
  18971. return result;
  18972. };
  18973. Geometry.prototype.setIndices = function (indices) {
  18974. if (this._indexBuffer) {
  18975. this._engine._releaseBuffer(this._indexBuffer);
  18976. }
  18977. this._indices = indices;
  18978. if (this._meshes.length !== 0 && this._indices) {
  18979. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18980. }
  18981. var meshes = this._meshes;
  18982. var numOfMeshes = meshes.length;
  18983. for (var index = 0; index < numOfMeshes; index++) {
  18984. meshes[index]._createGlobalSubMesh();
  18985. }
  18986. };
  18987. Geometry.prototype.getTotalIndices = function () {
  18988. if (!this.isReady()) {
  18989. return 0;
  18990. }
  18991. return this._indices.length;
  18992. };
  18993. Geometry.prototype.getIndices = function () {
  18994. if (!this.isReady()) {
  18995. return null;
  18996. }
  18997. return this._indices;
  18998. };
  18999. Geometry.prototype.getIndexBuffer = function () {
  19000. if (!this.isReady()) {
  19001. return null;
  19002. }
  19003. return this._indexBuffer;
  19004. };
  19005. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19006. var meshes = this._meshes;
  19007. var index = meshes.indexOf(mesh);
  19008. if (index === -1) {
  19009. return;
  19010. }
  19011. for (var kind in this._vertexBuffers) {
  19012. this._vertexBuffers[kind].dispose();
  19013. }
  19014. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19015. this._indexBuffer = null;
  19016. }
  19017. meshes.splice(index, 1);
  19018. mesh._geometry = null;
  19019. if (meshes.length == 0 && shouldDispose) {
  19020. this.dispose();
  19021. }
  19022. };
  19023. Geometry.prototype.applyToMesh = function (mesh) {
  19024. if (mesh._geometry === this) {
  19025. return;
  19026. }
  19027. var previousGeometry = mesh._geometry;
  19028. if (previousGeometry) {
  19029. previousGeometry.releaseForMesh(mesh);
  19030. }
  19031. var meshes = this._meshes;
  19032. mesh._geometry = this;
  19033. this._scene.pushGeometry(this);
  19034. meshes.push(mesh);
  19035. if (this.isReady()) {
  19036. this._applyToMesh(mesh);
  19037. } else {
  19038. mesh._boundingInfo = this._boundingInfo;
  19039. }
  19040. };
  19041. Geometry.prototype._applyToMesh = function (mesh) {
  19042. var numOfMeshes = this._meshes.length;
  19043. for (var kind in this._vertexBuffers) {
  19044. if (numOfMeshes === 1) {
  19045. this._vertexBuffers[kind].create();
  19046. }
  19047. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19048. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19049. mesh._resetPointsArrayCache();
  19050. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19051. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19052. mesh._createGlobalSubMesh();
  19053. }
  19054. }
  19055. if (numOfMeshes === 1 && this._indices) {
  19056. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19057. }
  19058. if (this._indexBuffer) {
  19059. this._indexBuffer.references = numOfMeshes;
  19060. }
  19061. };
  19062. Geometry.prototype.load = function (scene, onLoaded) {
  19063. var _this = this;
  19064. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19065. return;
  19066. }
  19067. if (this.isReady()) {
  19068. if (onLoaded) {
  19069. onLoaded();
  19070. }
  19071. return;
  19072. }
  19073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19074. scene._addPendingData(this);
  19075. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19076. _this._delayLoadingFunction(JSON.parse(data), _this);
  19077. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19078. _this._delayInfo = [];
  19079. scene._removePendingData(_this);
  19080. var meshes = _this._meshes;
  19081. var numOfMeshes = meshes.length;
  19082. for (var index = 0; index < numOfMeshes; index++) {
  19083. _this._applyToMesh(meshes[index]);
  19084. }
  19085. if (onLoaded) {
  19086. onLoaded();
  19087. }
  19088. }, function () {
  19089. }, scene.database);
  19090. };
  19091. Geometry.prototype.dispose = function () {
  19092. var meshes = this._meshes;
  19093. var numOfMeshes = meshes.length;
  19094. for (var index = 0; index < numOfMeshes; index++) {
  19095. this.releaseForMesh(meshes[index]);
  19096. }
  19097. this._meshes = [];
  19098. for (var kind in this._vertexBuffers) {
  19099. this._vertexBuffers[kind].dispose();
  19100. }
  19101. this._vertexBuffers = [];
  19102. this._totalVertices = 0;
  19103. if (this._indexBuffer) {
  19104. this._engine._releaseBuffer(this._indexBuffer);
  19105. }
  19106. this._indexBuffer = null;
  19107. this._indices = [];
  19108. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19109. this.delayLoadingFile = null;
  19110. this._delayLoadingFunction = null;
  19111. this._delayInfo = [];
  19112. this._boundingInfo = null;
  19113. var geometries = this._scene.getGeometries();
  19114. index = geometries.indexOf(this);
  19115. if (index > -1) {
  19116. geometries.splice(index, 1);
  19117. }
  19118. };
  19119. Geometry.prototype.copy = function (id) {
  19120. var vertexData = new BABYLON.VertexData();
  19121. vertexData.indices = [];
  19122. var indices = this.getIndices();
  19123. for (var index = 0; index < indices.length; index++) {
  19124. vertexData.indices.push(indices[index]);
  19125. }
  19126. var updatable = false;
  19127. var stopChecking = false;
  19128. for (var kind in this._vertexBuffers) {
  19129. vertexData.set(this.getVerticesData(kind), kind);
  19130. if (!stopChecking) {
  19131. updatable = this.getVertexBuffer(kind).isUpdatable();
  19132. stopChecking = !updatable;
  19133. }
  19134. }
  19135. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19136. geometry.delayLoadState = this.delayLoadState;
  19137. geometry.delayLoadingFile = this.delayLoadingFile;
  19138. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19139. for (kind in this._delayInfo) {
  19140. geometry._delayInfo = geometry._delayInfo || [];
  19141. geometry._delayInfo.push(kind);
  19142. }
  19143. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19144. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19145. return geometry;
  19146. };
  19147. Geometry.ExtractFromMesh = function (mesh, id) {
  19148. var geometry = mesh._geometry;
  19149. if (!geometry) {
  19150. return null;
  19151. }
  19152. return geometry.copy(id);
  19153. };
  19154. Geometry.RandomId = function () {
  19155. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19156. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19157. return v.toString(16);
  19158. });
  19159. };
  19160. return Geometry;
  19161. })();
  19162. BABYLON.Geometry = Geometry;
  19163. (function (Geometry) {
  19164. (function (Primitives) {
  19165. var _Primitive = (function (_super) {
  19166. __extends(_Primitive, _super);
  19167. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19168. this._beingRegenerated = true;
  19169. this._canBeRegenerated = canBeRegenerated;
  19170. _super.call(this, id, scene, vertexData, false, mesh);
  19171. this._beingRegenerated = false;
  19172. }
  19173. _Primitive.prototype.canBeRegenerated = function () {
  19174. return this._canBeRegenerated;
  19175. };
  19176. _Primitive.prototype.regenerate = function () {
  19177. if (!this._canBeRegenerated) {
  19178. return;
  19179. }
  19180. this._beingRegenerated = true;
  19181. this.setAllVerticesData(this._regenerateVertexData(), false);
  19182. this._beingRegenerated = false;
  19183. };
  19184. _Primitive.prototype.asNewGeometry = function (id) {
  19185. return _super.prototype.copy.call(this, id);
  19186. };
  19187. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19188. if (!this._beingRegenerated) {
  19189. return;
  19190. }
  19191. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19192. };
  19193. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19194. if (!this._beingRegenerated) {
  19195. return;
  19196. }
  19197. _super.prototype.setVerticesData.call(this, kind, data, false);
  19198. };
  19199. _Primitive.prototype._regenerateVertexData = function () {
  19200. throw new Error("Abstract method");
  19201. };
  19202. _Primitive.prototype.copy = function (id) {
  19203. throw new Error("Must be overriden in sub-classes.");
  19204. };
  19205. return _Primitive;
  19206. })(Geometry);
  19207. Primitives._Primitive = _Primitive;
  19208. var Box = (function (_super) {
  19209. __extends(Box, _super);
  19210. function Box(id, scene, size, canBeRegenerated, mesh) {
  19211. this.size = size;
  19212. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19213. }
  19214. Box.prototype._regenerateVertexData = function () {
  19215. return BABYLON.VertexData.CreateBox(this.size);
  19216. };
  19217. Box.prototype.copy = function (id) {
  19218. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19219. };
  19220. return Box;
  19221. })(_Primitive);
  19222. Primitives.Box = Box;
  19223. var Sphere = (function (_super) {
  19224. __extends(Sphere, _super);
  19225. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19226. this.segments = segments;
  19227. this.diameter = diameter;
  19228. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19229. }
  19230. Sphere.prototype._regenerateVertexData = function () {
  19231. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19232. };
  19233. Sphere.prototype.copy = function (id) {
  19234. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19235. };
  19236. return Sphere;
  19237. })(_Primitive);
  19238. Primitives.Sphere = Sphere;
  19239. var Cylinder = (function (_super) {
  19240. __extends(Cylinder, _super);
  19241. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19242. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19243. this.height = height;
  19244. this.diameterTop = diameterTop;
  19245. this.diameterBottom = diameterBottom;
  19246. this.tessellation = tessellation;
  19247. this.subdivisions = subdivisions;
  19248. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19249. }
  19250. Cylinder.prototype._regenerateVertexData = function () {
  19251. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19252. };
  19253. Cylinder.prototype.copy = function (id) {
  19254. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19255. };
  19256. return Cylinder;
  19257. })(_Primitive);
  19258. Primitives.Cylinder = Cylinder;
  19259. var Torus = (function (_super) {
  19260. __extends(Torus, _super);
  19261. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19262. this.diameter = diameter;
  19263. this.thickness = thickness;
  19264. this.tessellation = tessellation;
  19265. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19266. }
  19267. Torus.prototype._regenerateVertexData = function () {
  19268. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19269. };
  19270. Torus.prototype.copy = function (id) {
  19271. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19272. };
  19273. return Torus;
  19274. })(_Primitive);
  19275. Primitives.Torus = Torus;
  19276. var Ground = (function (_super) {
  19277. __extends(Ground, _super);
  19278. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19279. this.width = width;
  19280. this.height = height;
  19281. this.subdivisions = subdivisions;
  19282. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19283. }
  19284. Ground.prototype._regenerateVertexData = function () {
  19285. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19286. };
  19287. Ground.prototype.copy = function (id) {
  19288. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19289. };
  19290. return Ground;
  19291. })(_Primitive);
  19292. Primitives.Ground = Ground;
  19293. var TiledGround = (function (_super) {
  19294. __extends(TiledGround, _super);
  19295. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19296. this.xmin = xmin;
  19297. this.zmin = zmin;
  19298. this.xmax = xmax;
  19299. this.zmax = zmax;
  19300. this.subdivisions = subdivisions;
  19301. this.precision = precision;
  19302. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19303. }
  19304. TiledGround.prototype._regenerateVertexData = function () {
  19305. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19306. };
  19307. TiledGround.prototype.copy = function (id) {
  19308. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19309. };
  19310. return TiledGround;
  19311. })(_Primitive);
  19312. Primitives.TiledGround = TiledGround;
  19313. var Plane = (function (_super) {
  19314. __extends(Plane, _super);
  19315. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19316. this.size = size;
  19317. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19318. }
  19319. Plane.prototype._regenerateVertexData = function () {
  19320. return BABYLON.VertexData.CreatePlane(this.size);
  19321. };
  19322. Plane.prototype.copy = function (id) {
  19323. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19324. };
  19325. return Plane;
  19326. })(_Primitive);
  19327. Primitives.Plane = Plane;
  19328. var TorusKnot = (function (_super) {
  19329. __extends(TorusKnot, _super);
  19330. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19331. this.radius = radius;
  19332. this.tube = tube;
  19333. this.radialSegments = radialSegments;
  19334. this.tubularSegments = tubularSegments;
  19335. this.p = p;
  19336. this.q = q;
  19337. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19338. }
  19339. TorusKnot.prototype._regenerateVertexData = function () {
  19340. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19341. };
  19342. TorusKnot.prototype.copy = function (id) {
  19343. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19344. };
  19345. return TorusKnot;
  19346. })(_Primitive);
  19347. Primitives.TorusKnot = TorusKnot;
  19348. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19349. var Primitives = Geometry.Primitives;
  19350. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19351. var Geometry = BABYLON.Geometry;
  19352. })(BABYLON || (BABYLON = {}));
  19353. var __extends = this.__extends || function (d, b) {
  19354. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19355. function __() { this.constructor = d; }
  19356. __.prototype = b.prototype;
  19357. d.prototype = new __();
  19358. };
  19359. var BABYLON;
  19360. (function (BABYLON) {
  19361. var Gamepads = (function () {
  19362. function Gamepads(ongamedpadconnected) {
  19363. var _this = this;
  19364. this.babylonGamepads = [];
  19365. this.oneGamepadConnected = false;
  19366. this.isMonitoring = false;
  19367. this.gamepadEventSupported = 'GamepadEvent' in window;
  19368. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19369. 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=";
  19370. this._callbackGamepadConnected = ongamedpadconnected;
  19371. if (this.gamepadSupportAvailable) {
  19372. if (this.gamepadEventSupported) {
  19373. window.addEventListener('gamepadconnected', function (evt) {
  19374. _this._onGamepadConnected(evt);
  19375. }, false);
  19376. window.addEventListener('gamepaddisconnected', function (evt) {
  19377. _this._onGamepadDisconnected(evt);
  19378. }, false);
  19379. } else {
  19380. this._startMonitoringGamepads();
  19381. }
  19382. if (!this.oneGamepadConnected) {
  19383. this._insertGamepadDOMInstructions();
  19384. }
  19385. } else {
  19386. this._insertGamepadDOMNotSupported();
  19387. }
  19388. }
  19389. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19390. Gamepads.gamepadDOMInfo = document.createElement("div");
  19391. var buttonAImage = document.createElement("img");
  19392. buttonAImage.src = this.buttonADataURL;
  19393. var spanMessage = document.createElement("span");
  19394. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19395. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19396. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19397. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19398. Gamepads.gamepadDOMInfo.style.width = "100%";
  19399. Gamepads.gamepadDOMInfo.style.height = "48px";
  19400. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19401. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19402. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19403. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19404. buttonAImage.style.position = "relative";
  19405. buttonAImage.style.bottom = "8px";
  19406. spanMessage.style.position = "relative";
  19407. spanMessage.style.fontSize = "32px";
  19408. spanMessage.style.bottom = "32px";
  19409. spanMessage.style.color = "green";
  19410. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19411. };
  19412. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19413. Gamepads.gamepadDOMInfo = document.createElement("div");
  19414. var spanMessage = document.createElement("span");
  19415. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19416. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19417. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19418. Gamepads.gamepadDOMInfo.style.width = "100%";
  19419. Gamepads.gamepadDOMInfo.style.height = "40px";
  19420. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19421. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19422. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19423. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19424. spanMessage.style.position = "relative";
  19425. spanMessage.style.fontSize = "32px";
  19426. spanMessage.style.color = "red";
  19427. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19428. };
  19429. Gamepads.prototype.dispose = function () {
  19430. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19431. };
  19432. Gamepads.prototype._onGamepadConnected = function (evt) {
  19433. var newGamepad = this._addNewGamepad(evt.gamepad);
  19434. if (this._callbackGamepadConnected)
  19435. this._callbackGamepadConnected(newGamepad);
  19436. this._startMonitoringGamepads();
  19437. };
  19438. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19439. if (!this.oneGamepadConnected) {
  19440. this.oneGamepadConnected = true;
  19441. if (Gamepads.gamepadDOMInfo) {
  19442. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19443. Gamepads.gamepadDOMInfo = null;
  19444. }
  19445. }
  19446. var newGamepad;
  19447. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19448. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19449. } else {
  19450. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19451. }
  19452. this.babylonGamepads.push(newGamepad);
  19453. return newGamepad;
  19454. };
  19455. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19456. for (var i in this.babylonGamepads) {
  19457. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19458. this.babylonGamepads.splice(i, 1);
  19459. break;
  19460. }
  19461. }
  19462. if (this.babylonGamepads.length == 0) {
  19463. this._stopMonitoringGamepads();
  19464. }
  19465. };
  19466. Gamepads.prototype._startMonitoringGamepads = function () {
  19467. if (!this.isMonitoring) {
  19468. this.isMonitoring = true;
  19469. this._checkGamepadsStatus();
  19470. }
  19471. };
  19472. Gamepads.prototype._stopMonitoringGamepads = function () {
  19473. this.isMonitoring = false;
  19474. };
  19475. Gamepads.prototype._checkGamepadsStatus = function () {
  19476. var _this = this;
  19477. this._updateGamepadObjects();
  19478. for (var i in this.babylonGamepads) {
  19479. this.babylonGamepads[i].update();
  19480. }
  19481. if (this.isMonitoring) {
  19482. if (window.requestAnimationFrame) {
  19483. window.requestAnimationFrame(function () {
  19484. _this._checkGamepadsStatus();
  19485. });
  19486. } else if (window.mozRequestAnimationFrame) {
  19487. window.mozRequestAnimationFrame(function () {
  19488. _this._checkGamepadsStatus();
  19489. });
  19490. } else if (window.webkitRequestAnimationFrame) {
  19491. window.webkitRequestAnimationFrame(function () {
  19492. _this._checkGamepadsStatus();
  19493. });
  19494. }
  19495. }
  19496. };
  19497. Gamepads.prototype._updateGamepadObjects = function () {
  19498. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19499. for (var i = 0; i < gamepads.length; i++) {
  19500. if (gamepads[i]) {
  19501. if (!(gamepads[i].index in this.babylonGamepads)) {
  19502. var newGamepad = this._addNewGamepad(gamepads[i]);
  19503. if (this._callbackGamepadConnected) {
  19504. this._callbackGamepadConnected(newGamepad);
  19505. }
  19506. } else {
  19507. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19508. }
  19509. }
  19510. }
  19511. };
  19512. return Gamepads;
  19513. })();
  19514. BABYLON.Gamepads = Gamepads;
  19515. var StickValues = (function () {
  19516. function StickValues(x, y) {
  19517. this.x = x;
  19518. this.y = y;
  19519. }
  19520. return StickValues;
  19521. })();
  19522. BABYLON.StickValues = StickValues;
  19523. var Gamepad = (function () {
  19524. function Gamepad(id, index, browserGamepad) {
  19525. this.id = id;
  19526. this.index = index;
  19527. this.browserGamepad = browserGamepad;
  19528. if (this.browserGamepad.axes.length >= 2) {
  19529. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19530. }
  19531. if (this.browserGamepad.axes.length >= 4) {
  19532. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19533. }
  19534. }
  19535. Gamepad.prototype.onleftstickchanged = function (callback) {
  19536. this._onleftstickchanged = callback;
  19537. };
  19538. Gamepad.prototype.onrightstickchanged = function (callback) {
  19539. this._onrightstickchanged = callback;
  19540. };
  19541. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19542. get: function () {
  19543. return this._leftStick;
  19544. },
  19545. set: function (newValues) {
  19546. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19547. this._onleftstickchanged(newValues);
  19548. }
  19549. this._leftStick = newValues;
  19550. },
  19551. enumerable: true,
  19552. configurable: true
  19553. });
  19554. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19555. get: function () {
  19556. return this._rightStick;
  19557. },
  19558. set: function (newValues) {
  19559. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19560. this._onrightstickchanged(newValues);
  19561. }
  19562. this._rightStick = newValues;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Gamepad.prototype.update = function () {
  19568. if (this._leftStick) {
  19569. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19570. }
  19571. if (this._rightStick) {
  19572. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19573. }
  19574. };
  19575. return Gamepad;
  19576. })();
  19577. BABYLON.Gamepad = Gamepad;
  19578. var GenericPad = (function (_super) {
  19579. __extends(GenericPad, _super);
  19580. function GenericPad(id, index, gamepad) {
  19581. _super.call(this, id, index, gamepad);
  19582. this.id = id;
  19583. this.index = index;
  19584. this.gamepad = gamepad;
  19585. this._buttons = new Array(gamepad.buttons.length);
  19586. }
  19587. GenericPad.prototype.onbuttondown = function (callback) {
  19588. this._onbuttondown = callback;
  19589. };
  19590. GenericPad.prototype.onbuttonup = function (callback) {
  19591. this._onbuttonup = callback;
  19592. };
  19593. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19594. if (newValue !== currentValue) {
  19595. if (this._onbuttondown && newValue === 1) {
  19596. this._onbuttondown(buttonIndex);
  19597. }
  19598. if (this._onbuttonup && newValue === 0) {
  19599. this._onbuttonup(buttonIndex);
  19600. }
  19601. }
  19602. return newValue;
  19603. };
  19604. GenericPad.prototype.update = function () {
  19605. _super.prototype.update.call(this);
  19606. for (var index = 0; index < this._buttons.length; index++) {
  19607. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19608. }
  19609. };
  19610. return GenericPad;
  19611. })(Gamepad);
  19612. BABYLON.GenericPad = GenericPad;
  19613. (function (Xbox360Button) {
  19614. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19615. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19616. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19617. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19618. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19619. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19620. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19621. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19622. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19623. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19624. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19625. var Xbox360Button = BABYLON.Xbox360Button;
  19626. (function (Xbox360Dpad) {
  19627. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19628. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19629. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19630. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19631. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19632. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19633. var Xbox360Pad = (function (_super) {
  19634. __extends(Xbox360Pad, _super);
  19635. function Xbox360Pad() {
  19636. _super.apply(this, arguments);
  19637. this._leftTrigger = 0;
  19638. this._rightTrigger = 0;
  19639. this._buttonA = 0;
  19640. this._buttonB = 0;
  19641. this._buttonX = 0;
  19642. this._buttonY = 0;
  19643. this._buttonBack = 0;
  19644. this._buttonStart = 0;
  19645. this._buttonLB = 0;
  19646. this._buttonRB = 0;
  19647. this._buttonLeftStick = 0;
  19648. this._buttonRightStick = 0;
  19649. this._dPadUp = 0;
  19650. this._dPadDown = 0;
  19651. this._dPadLeft = 0;
  19652. this._dPadRight = 0;
  19653. }
  19654. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19655. this._onlefttriggerchanged = callback;
  19656. };
  19657. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19658. this._onrighttriggerchanged = callback;
  19659. };
  19660. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19661. get: function () {
  19662. return this._leftTrigger;
  19663. },
  19664. set: function (newValue) {
  19665. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19666. this._onlefttriggerchanged(newValue);
  19667. }
  19668. this._leftTrigger = newValue;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19674. get: function () {
  19675. return this._rightTrigger;
  19676. },
  19677. set: function (newValue) {
  19678. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19679. this._onrighttriggerchanged(newValue);
  19680. }
  19681. this._rightTrigger = newValue;
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19687. this._onbuttondown = callback;
  19688. };
  19689. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19690. this._onbuttonup = callback;
  19691. };
  19692. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19693. this._ondpaddown = callback;
  19694. };
  19695. Xbox360Pad.prototype.ondpadup = function (callback) {
  19696. this._ondpadup = callback;
  19697. };
  19698. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19699. if (newValue !== currentValue) {
  19700. if (this._onbuttondown && newValue === 1) {
  19701. this._onbuttondown(buttonType);
  19702. }
  19703. if (this._onbuttonup && newValue === 0) {
  19704. this._onbuttonup(buttonType);
  19705. }
  19706. }
  19707. return newValue;
  19708. };
  19709. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19710. if (newValue !== currentValue) {
  19711. if (this._ondpaddown && newValue === 1) {
  19712. this._ondpaddown(buttonType);
  19713. }
  19714. if (this._ondpadup && newValue === 0) {
  19715. this._ondpadup(buttonType);
  19716. }
  19717. }
  19718. return newValue;
  19719. };
  19720. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19721. get: function () {
  19722. return this._buttonA;
  19723. },
  19724. set: function (value) {
  19725. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19731. get: function () {
  19732. return this._buttonB;
  19733. },
  19734. set: function (value) {
  19735. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19741. get: function () {
  19742. return this._buttonX;
  19743. },
  19744. set: function (value) {
  19745. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19751. get: function () {
  19752. return this._buttonY;
  19753. },
  19754. set: function (value) {
  19755. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19761. get: function () {
  19762. return this._buttonStart;
  19763. },
  19764. set: function (value) {
  19765. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19771. get: function () {
  19772. return this._buttonBack;
  19773. },
  19774. set: function (value) {
  19775. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19781. get: function () {
  19782. return this._buttonLB;
  19783. },
  19784. set: function (value) {
  19785. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19791. get: function () {
  19792. return this._buttonRB;
  19793. },
  19794. set: function (value) {
  19795. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19801. get: function () {
  19802. return this._buttonLeftStick;
  19803. },
  19804. set: function (value) {
  19805. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19811. get: function () {
  19812. return this._buttonRightStick;
  19813. },
  19814. set: function (value) {
  19815. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19821. get: function () {
  19822. return this._dPadUp;
  19823. },
  19824. set: function (value) {
  19825. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19831. get: function () {
  19832. return this._dPadDown;
  19833. },
  19834. set: function (value) {
  19835. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19841. get: function () {
  19842. return this._dPadLeft;
  19843. },
  19844. set: function (value) {
  19845. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19851. get: function () {
  19852. return this._dPadRight;
  19853. },
  19854. set: function (value) {
  19855. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Xbox360Pad.prototype.update = function () {
  19861. _super.prototype.update.call(this);
  19862. this.buttonA = this.browserGamepad.buttons[0].value;
  19863. this.buttonB = this.browserGamepad.buttons[1].value;
  19864. this.buttonX = this.browserGamepad.buttons[2].value;
  19865. this.buttonY = this.browserGamepad.buttons[3].value;
  19866. this.buttonLB = this.browserGamepad.buttons[4].value;
  19867. this.buttonRB = this.browserGamepad.buttons[5].value;
  19868. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19869. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19870. this.buttonBack = this.browserGamepad.buttons[8].value;
  19871. this.buttonStart = this.browserGamepad.buttons[9].value;
  19872. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19873. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19874. this.dPadUp = this.browserGamepad.buttons[12].value;
  19875. this.dPadDown = this.browserGamepad.buttons[13].value;
  19876. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19877. this.dPadRight = this.browserGamepad.buttons[15].value;
  19878. };
  19879. return Xbox360Pad;
  19880. })(Gamepad);
  19881. BABYLON.Xbox360Pad = Xbox360Pad;
  19882. })(BABYLON || (BABYLON = {}));
  19883. var __extends = this.__extends || function (d, b) {
  19884. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19885. function __() { this.constructor = d; }
  19886. __.prototype = b.prototype;
  19887. d.prototype = new __();
  19888. };
  19889. var BABYLON;
  19890. (function (BABYLON) {
  19891. var GamepadCamera = (function (_super) {
  19892. __extends(GamepadCamera, _super);
  19893. function GamepadCamera(name, position, scene) {
  19894. var _this = this;
  19895. _super.call(this, name, position, scene);
  19896. this.angularSensibility = 200;
  19897. this.moveSensibility = 75;
  19898. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19899. _this._onNewGameConnected(gamepad);
  19900. });
  19901. }
  19902. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19903. if (gamepad.index === 0) {
  19904. this._gamepad = gamepad;
  19905. }
  19906. };
  19907. GamepadCamera.prototype._checkInputs = function () {
  19908. if (!this._gamepad) {
  19909. return;
  19910. }
  19911. var LSValues = this._gamepad.leftStick;
  19912. var normalizedLX = LSValues.x / this.moveSensibility;
  19913. var normalizedLY = LSValues.y / this.moveSensibility;
  19914. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19915. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19916. var RSValues = this._gamepad.rightStick;
  19917. var normalizedRX = RSValues.x / this.angularSensibility;
  19918. var normalizedRY = RSValues.y / this.angularSensibility;
  19919. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19920. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19921. ;
  19922. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19923. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19924. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19925. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19926. };
  19927. GamepadCamera.prototype.dispose = function () {
  19928. this._gamepads.dispose();
  19929. _super.prototype.dispose.call(this);
  19930. };
  19931. return GamepadCamera;
  19932. })(BABYLON.FreeCamera);
  19933. BABYLON.GamepadCamera = GamepadCamera;
  19934. })(BABYLON || (BABYLON = {}));
  19935. var __extends = this.__extends || function (d, b) {
  19936. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19937. function __() { this.constructor = d; }
  19938. __.prototype = b.prototype;
  19939. d.prototype = new __();
  19940. };
  19941. var BABYLON;
  19942. (function (BABYLON) {
  19943. var LinesMesh = (function (_super) {
  19944. __extends(LinesMesh, _super);
  19945. function LinesMesh(name, scene, updatable) {
  19946. if (typeof updatable === "undefined") { updatable = false; }
  19947. _super.call(this, name, scene);
  19948. this.color = new BABYLON.Color3(1, 1, 1);
  19949. this.alpha = 1;
  19950. this._indices = new Array();
  19951. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19952. attributes: ["position"],
  19953. uniforms: ["worldViewProjection", "color"],
  19954. needAlphaBlending: true
  19955. });
  19956. }
  19957. Object.defineProperty(LinesMesh.prototype, "material", {
  19958. get: function () {
  19959. return this._colorShader;
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19965. get: function () {
  19966. return false;
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19972. get: function () {
  19973. return false;
  19974. },
  19975. enumerable: true,
  19976. configurable: true
  19977. });
  19978. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19979. var engine = this.getScene().getEngine();
  19980. var indexToBind = this._geometry.getIndexBuffer();
  19981. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19982. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19983. };
  19984. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19985. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19986. return;
  19987. }
  19988. var engine = this.getScene().getEngine();
  19989. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19990. };
  19991. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19992. return null;
  19993. };
  19994. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19995. this._colorShader.dispose();
  19996. _super.prototype.dispose.call(this, doNotRecurse);
  19997. };
  19998. return LinesMesh;
  19999. })(BABYLON.Mesh);
  20000. BABYLON.LinesMesh = LinesMesh;
  20001. })(BABYLON || (BABYLON = {}));
  20002. var BABYLON;
  20003. (function (BABYLON) {
  20004. var OutlineRenderer = (function () {
  20005. function OutlineRenderer(scene) {
  20006. this._scene = scene;
  20007. }
  20008. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20009. var scene = this._scene;
  20010. var engine = this._scene.getEngine();
  20011. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20012. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20013. return;
  20014. }
  20015. var mesh = subMesh.getRenderingMesh();
  20016. var material = subMesh.getMaterial();
  20017. engine.enableEffect(this._effect);
  20018. this._effect.setFloat("offset", mesh.outlineWidth);
  20019. this._effect.setColor3("color", mesh.outlineColor);
  20020. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20021. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20022. if (useBones) {
  20023. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20024. }
  20025. mesh._bind(subMesh, this._effect, false);
  20026. if (material && material.needAlphaTesting()) {
  20027. var alphaTexture = material.getAlphaTestTexture();
  20028. this._effect.setTexture("diffuseSampler", alphaTexture);
  20029. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20030. }
  20031. if (hardwareInstancedRendering) {
  20032. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20033. } else {
  20034. if (batch.renderSelf[subMesh._id]) {
  20035. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20036. mesh._draw(subMesh, true);
  20037. }
  20038. if (batch.visibleInstances[subMesh._id]) {
  20039. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20040. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20041. this._effect.setMatrix("world", instance.getWorldMatrix());
  20042. mesh._draw(subMesh, true);
  20043. }
  20044. }
  20045. }
  20046. };
  20047. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20048. var defines = [];
  20049. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20050. var mesh = subMesh.getMesh();
  20051. var material = subMesh.getMaterial();
  20052. if (material && material.needAlphaTesting()) {
  20053. defines.push("#define ALPHATEST");
  20054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20055. attribs.push(BABYLON.VertexBuffer.UVKind);
  20056. defines.push("#define UV1");
  20057. }
  20058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20059. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20060. defines.push("#define UV2");
  20061. }
  20062. }
  20063. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20064. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20065. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20066. defines.push("#define BONES");
  20067. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20068. }
  20069. if (useInstances) {
  20070. defines.push("#define INSTANCES");
  20071. attribs.push("world0");
  20072. attribs.push("world1");
  20073. attribs.push("world2");
  20074. attribs.push("world3");
  20075. }
  20076. var join = defines.join("\n");
  20077. if (this._cachedDefines != join) {
  20078. this._cachedDefines = join;
  20079. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20080. }
  20081. return this._effect.isReady();
  20082. };
  20083. return OutlineRenderer;
  20084. })();
  20085. BABYLON.OutlineRenderer = OutlineRenderer;
  20086. })(BABYLON || (BABYLON = {}));
  20087. var BABYLON;
  20088. (function (BABYLON) {
  20089. var MeshAssetTask = (function () {
  20090. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20091. this.name = name;
  20092. this.meshesNames = meshesNames;
  20093. this.rootUrl = rootUrl;
  20094. this.sceneFilename = sceneFilename;
  20095. this.isCompleted = false;
  20096. }
  20097. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20098. var _this = this;
  20099. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20100. _this.loadedMeshes = meshes;
  20101. _this.loadedParticleSystems = particleSystems;
  20102. _this.loadedSkeletons = skeletons;
  20103. _this.isCompleted = true;
  20104. if (_this.onSuccess) {
  20105. _this.onSuccess(_this);
  20106. }
  20107. onSuccess();
  20108. }, null, function () {
  20109. if (_this.onError) {
  20110. _this.onError(_this);
  20111. }
  20112. onError();
  20113. });
  20114. };
  20115. return MeshAssetTask;
  20116. })();
  20117. BABYLON.MeshAssetTask = MeshAssetTask;
  20118. var TextFileAssetTask = (function () {
  20119. function TextFileAssetTask(name, url) {
  20120. this.name = name;
  20121. this.url = url;
  20122. this.isCompleted = false;
  20123. }
  20124. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20125. var _this = this;
  20126. BABYLON.Tools.LoadFile(this.url, function (data) {
  20127. _this.text = data;
  20128. _this.isCompleted = true;
  20129. if (_this.onSuccess) {
  20130. _this.onSuccess(_this);
  20131. }
  20132. onSuccess();
  20133. }, null, scene.database, false, function () {
  20134. if (_this.onError) {
  20135. _this.onError(_this);
  20136. }
  20137. onError();
  20138. });
  20139. };
  20140. return TextFileAssetTask;
  20141. })();
  20142. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20143. var BinaryFileAssetTask = (function () {
  20144. function BinaryFileAssetTask(name, url) {
  20145. this.name = name;
  20146. this.url = url;
  20147. this.isCompleted = false;
  20148. }
  20149. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20150. var _this = this;
  20151. BABYLON.Tools.LoadFile(this.url, function (data) {
  20152. _this.data = data;
  20153. _this.isCompleted = true;
  20154. if (_this.onSuccess) {
  20155. _this.onSuccess(_this);
  20156. }
  20157. onSuccess();
  20158. }, null, scene.database, true, function () {
  20159. if (_this.onError) {
  20160. _this.onError(_this);
  20161. }
  20162. onError();
  20163. });
  20164. };
  20165. return BinaryFileAssetTask;
  20166. })();
  20167. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20168. var ImageAssetTask = (function () {
  20169. function ImageAssetTask(name, url) {
  20170. this.name = name;
  20171. this.url = url;
  20172. this.isCompleted = false;
  20173. }
  20174. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20175. var _this = this;
  20176. var img = new Image();
  20177. img.onload = function () {
  20178. _this.image = img;
  20179. _this.isCompleted = true;
  20180. if (_this.onSuccess) {
  20181. _this.onSuccess(_this);
  20182. }
  20183. onSuccess();
  20184. };
  20185. img.onerror = function () {
  20186. if (_this.onError) {
  20187. _this.onError(_this);
  20188. }
  20189. onError();
  20190. };
  20191. img.src = this.url;
  20192. };
  20193. return ImageAssetTask;
  20194. })();
  20195. BABYLON.ImageAssetTask = ImageAssetTask;
  20196. var TextureAssetTask = (function () {
  20197. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  20198. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20199. this.name = name;
  20200. this.url = url;
  20201. this.noMipmap = noMipmap;
  20202. this.invertY = invertY;
  20203. this.samplingMode = samplingMode;
  20204. this.isCompleted = false;
  20205. }
  20206. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20207. var _this = this;
  20208. var onload = function () {
  20209. _this.isCompleted = true;
  20210. if (_this.onSuccess) {
  20211. _this.onSuccess(_this);
  20212. }
  20213. onSuccess();
  20214. };
  20215. var onerror = function () {
  20216. if (_this.onError) {
  20217. _this.onError(_this);
  20218. }
  20219. onError();
  20220. };
  20221. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  20222. };
  20223. return TextureAssetTask;
  20224. })();
  20225. BABYLON.TextureAssetTask = TextureAssetTask;
  20226. var AssetsManager = (function () {
  20227. function AssetsManager(scene) {
  20228. this._tasks = new Array();
  20229. this._waitingTasksCount = 0;
  20230. this.useDefaultLoadingScreen = true;
  20231. this._scene = scene;
  20232. }
  20233. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20234. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20235. this._tasks.push(task);
  20236. return task;
  20237. };
  20238. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20239. var task = new TextFileAssetTask(taskName, url);
  20240. this._tasks.push(task);
  20241. return task;
  20242. };
  20243. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20244. var task = new BinaryFileAssetTask(taskName, url);
  20245. this._tasks.push(task);
  20246. return task;
  20247. };
  20248. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20249. var task = new ImageAssetTask(taskName, url);
  20250. this._tasks.push(task);
  20251. return task;
  20252. };
  20253. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  20254. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20255. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  20256. this._tasks.push(task);
  20257. return task;
  20258. };
  20259. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20260. this._waitingTasksCount--;
  20261. if (this._waitingTasksCount === 0) {
  20262. if (this.onFinish) {
  20263. this.onFinish(this._tasks);
  20264. }
  20265. this._scene.getEngine().hideLoadingUI();
  20266. }
  20267. };
  20268. AssetsManager.prototype._runTask = function (task) {
  20269. var _this = this;
  20270. task.run(this._scene, function () {
  20271. if (_this.onTaskSuccess) {
  20272. _this.onTaskSuccess(task);
  20273. }
  20274. _this._decreaseWaitingTasksCount();
  20275. }, function () {
  20276. if (_this.onTaskError) {
  20277. _this.onTaskError(task);
  20278. }
  20279. _this._decreaseWaitingTasksCount();
  20280. });
  20281. };
  20282. AssetsManager.prototype.reset = function () {
  20283. this._tasks = new Array();
  20284. return this;
  20285. };
  20286. AssetsManager.prototype.load = function () {
  20287. this._waitingTasksCount = this._tasks.length;
  20288. if (this._waitingTasksCount === 0) {
  20289. if (this.onFinish) {
  20290. this.onFinish(this._tasks);
  20291. }
  20292. return this;
  20293. }
  20294. if (this.useDefaultLoadingScreen) {
  20295. this._scene.getEngine().displayLoadingUI();
  20296. }
  20297. for (var index = 0; index < this._tasks.length; index++) {
  20298. var task = this._tasks[index];
  20299. this._runTask(task);
  20300. }
  20301. return this;
  20302. };
  20303. return AssetsManager;
  20304. })();
  20305. BABYLON.AssetsManager = AssetsManager;
  20306. })(BABYLON || (BABYLON = {}));
  20307. var __extends = this.__extends || function (d, b) {
  20308. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20309. function __() { this.constructor = d; }
  20310. __.prototype = b.prototype;
  20311. d.prototype = new __();
  20312. };
  20313. var BABYLON;
  20314. (function (BABYLON) {
  20315. var VRDeviceOrientationCamera = (function (_super) {
  20316. __extends(VRDeviceOrientationCamera, _super);
  20317. function VRDeviceOrientationCamera(name, position, scene) {
  20318. _super.call(this, name, position, scene);
  20319. this._alpha = 0;
  20320. this._beta = 0;
  20321. this._gamma = 0;
  20322. }
  20323. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20324. this._alpha = +evt.alpha | 0;
  20325. this._beta = +evt.beta | 0;
  20326. this._gamma = +evt.gamma | 0;
  20327. if (this._gamma < 0) {
  20328. this._gamma = 90 + this._gamma;
  20329. } else {
  20330. this._gamma = 270 - this._gamma;
  20331. }
  20332. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20333. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20334. this.rotation.z = this._beta / 180.0 * Math.PI;
  20335. };
  20336. return VRDeviceOrientationCamera;
  20337. })(BABYLON.OculusCamera);
  20338. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20339. })(BABYLON || (BABYLON = {}));
  20340. var __extends = this.__extends || function (d, b) {
  20341. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20342. function __() { this.constructor = d; }
  20343. __.prototype = b.prototype;
  20344. d.prototype = new __();
  20345. };
  20346. var BABYLON;
  20347. (function (BABYLON) {
  20348. var WebVRCamera = (function (_super) {
  20349. __extends(WebVRCamera, _super);
  20350. function WebVRCamera(name, position, scene) {
  20351. _super.call(this, name, position, scene);
  20352. this._hmdDevice = null;
  20353. this._sensorDevice = null;
  20354. this._cacheState = null;
  20355. this._cacheQuaternion = new BABYLON.Quaternion();
  20356. this._cacheRotation = BABYLON.Vector3.Zero();
  20357. this._vrEnabled = false;
  20358. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  20359. }
  20360. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  20361. var size = devices.length;
  20362. var i = 0;
  20363. this._sensorDevice = null;
  20364. this._hmdDevice = null;
  20365. while (i < size && this._hmdDevice === null) {
  20366. if (devices[i] instanceof HMDVRDevice) {
  20367. this._hmdDevice = devices[i];
  20368. }
  20369. i++;
  20370. }
  20371. i = 0;
  20372. while (i < size && this._sensorDevice === null) {
  20373. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  20374. this._sensorDevice = devices[i];
  20375. }
  20376. i++;
  20377. }
  20378. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  20379. };
  20380. WebVRCamera.prototype._update = function () {
  20381. if (this._vrEnabled) {
  20382. this._cacheState = this._sensorDevice.getState();
  20383. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  20384. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  20385. this.rotation.x = -this._cacheRotation.z;
  20386. this.rotation.y = -this._cacheRotation.y;
  20387. this.rotation.z = this._cacheRotation.x;
  20388. }
  20389. _super.prototype._update.call(this);
  20390. };
  20391. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  20392. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20393. if (navigator.getVRDevices) {
  20394. navigator.getVRDevices().then(this._getWebVRDevices);
  20395. } else if (navigator.mozGetVRDevices) {
  20396. navigator.mozGetVRDevices(this._getWebVRDevices);
  20397. }
  20398. };
  20399. WebVRCamera.prototype.detachControl = function (element) {
  20400. _super.prototype.detachControl.call(this, element);
  20401. this._vrEnabled = false;
  20402. };
  20403. return WebVRCamera;
  20404. })(BABYLON.OculusCamera);
  20405. BABYLON.WebVRCamera = WebVRCamera;
  20406. })(BABYLON || (BABYLON = {}));