babylon.1.14-beta-debug.js 1007 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.multiplyInPlace = function (otherVector) {
  238. this.x *= otherVector.x;
  239. this.y *= otherVector.y;
  240. };
  241. Vector2.prototype.multiply = function (otherVector) {
  242. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  243. };
  244. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  245. result.x = this.x * otherVector.x;
  246. result.y = this.y * otherVector.y;
  247. };
  248. Vector2.prototype.multiplyByFloats = function (x, y) {
  249. return new Vector2(this.x * x, this.y * y);
  250. };
  251. Vector2.prototype.divide = function (otherVector) {
  252. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  253. };
  254. Vector2.prototype.divideToRef = function (otherVector, result) {
  255. result.x = this.x / otherVector.x;
  256. result.y = this.y / otherVector.y;
  257. };
  258. Vector2.prototype.negate = function () {
  259. return new Vector2(-this.x, -this.y);
  260. };
  261. Vector2.prototype.scaleInPlace = function (scale) {
  262. this.x *= scale;
  263. this.y *= scale;
  264. };
  265. Vector2.prototype.scale = function (scale) {
  266. return new Vector2(this.x * scale, this.y * scale);
  267. };
  268. Vector2.prototype.equals = function (otherVector) {
  269. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  270. };
  271. Vector2.prototype.length = function () {
  272. return Math.sqrt(this.x * this.x + this.y * this.y);
  273. };
  274. Vector2.prototype.lengthSquared = function () {
  275. return (this.x * this.x + this.y * this.y);
  276. };
  277. Vector2.prototype.normalize = function () {
  278. var len = this.length();
  279. if (len === 0)
  280. return;
  281. var num = 1.0 / len;
  282. this.x *= num;
  283. this.y *= num;
  284. };
  285. Vector2.prototype.clone = function () {
  286. return new Vector2(this.x, this.y);
  287. };
  288. Vector2.Zero = function () {
  289. return new Vector2(0, 0);
  290. };
  291. Vector2.FromArray = function (array, offset) {
  292. if (!offset) {
  293. offset = 0;
  294. }
  295. return new Vector2(array[offset], array[offset + 1]);
  296. };
  297. Vector2.FromArrayToRef = function (array, offset, result) {
  298. result.x = array[offset];
  299. result.y = array[offset + 1];
  300. };
  301. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  302. var squared = amount * amount;
  303. var cubed = amount * squared;
  304. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  305. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  306. return new Vector2(x, y);
  307. };
  308. Vector2.Clamp = function (value, min, max) {
  309. var x = value.x;
  310. x = (x > max.x) ? max.x : x;
  311. x = (x < min.x) ? min.x : x;
  312. var y = value.y;
  313. y = (y > max.y) ? max.y : y;
  314. y = (y < min.y) ? min.y : y;
  315. return new Vector2(x, y);
  316. };
  317. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  318. var squared = amount * amount;
  319. var cubed = amount * squared;
  320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  322. var part3 = (cubed - (2.0 * squared)) + amount;
  323. var part4 = cubed - squared;
  324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  326. return new Vector2(x, y);
  327. };
  328. Vector2.Lerp = function (start, end, amount) {
  329. var x = start.x + ((end.x - start.x) * amount);
  330. var y = start.y + ((end.y - start.y) * amount);
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Dot = function (left, right) {
  334. return left.x * right.x + left.y * right.y;
  335. };
  336. Vector2.Normalize = function (vector) {
  337. var newVector = vector.clone();
  338. newVector.normalize();
  339. return newVector;
  340. };
  341. Vector2.Minimize = function (left, right) {
  342. var x = (left.x < right.x) ? left.x : right.x;
  343. var y = (left.y < right.y) ? left.y : right.y;
  344. return new Vector2(x, y);
  345. };
  346. Vector2.Maximize = function (left, right) {
  347. var x = (left.x > right.x) ? left.x : right.x;
  348. var y = (left.y > right.y) ? left.y : right.y;
  349. return new Vector2(x, y);
  350. };
  351. Vector2.Transform = function (vector, transformation) {
  352. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  353. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Distance = function (value1, value2) {
  357. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  358. };
  359. Vector2.DistanceSquared = function (value1, value2) {
  360. var x = value1.x - value2.x;
  361. var y = value1.y - value2.y;
  362. return (x * x) + (y * y);
  363. };
  364. return Vector2;
  365. })();
  366. BABYLON.Vector2 = Vector2;
  367. var Vector3 = (function () {
  368. function Vector3(x, y, z) {
  369. this.x = x;
  370. this.y = y;
  371. this.z = z;
  372. }
  373. Vector3.prototype.toString = function () {
  374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  375. };
  376. Vector3.prototype.asArray = function () {
  377. var result = [];
  378. this.toArray(result, 0);
  379. return result;
  380. };
  381. Vector3.prototype.toArray = function (array, index) {
  382. if (index === undefined) {
  383. index = 0;
  384. }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. array[index + 2] = this.z;
  388. };
  389. Vector3.prototype.addInPlace = function (otherVector) {
  390. this.x += otherVector.x;
  391. this.y += otherVector.y;
  392. this.z += otherVector.z;
  393. };
  394. Vector3.prototype.add = function (otherVector) {
  395. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  396. };
  397. Vector3.prototype.addToRef = function (otherVector, result) {
  398. result.x = this.x + otherVector.x;
  399. result.y = this.y + otherVector.y;
  400. result.z = this.z + otherVector.z;
  401. };
  402. Vector3.prototype.subtractInPlace = function (otherVector) {
  403. this.x -= otherVector.x;
  404. this.y -= otherVector.y;
  405. this.z -= otherVector.z;
  406. };
  407. Vector3.prototype.subtract = function (otherVector) {
  408. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  409. };
  410. Vector3.prototype.subtractToRef = function (otherVector, result) {
  411. result.x = this.x - otherVector.x;
  412. result.y = this.y - otherVector.y;
  413. result.z = this.z - otherVector.z;
  414. };
  415. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  416. return new Vector3(this.x - x, this.y - y, this.z - z);
  417. };
  418. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  419. result.x = this.x - x;
  420. result.y = this.y - y;
  421. result.z = this.z - z;
  422. };
  423. Vector3.prototype.negate = function () {
  424. return new Vector3(-this.x, -this.y, -this.z);
  425. };
  426. Vector3.prototype.scaleInPlace = function (scale) {
  427. this.x *= scale;
  428. this.y *= scale;
  429. this.z *= scale;
  430. };
  431. Vector3.prototype.scale = function (scale) {
  432. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  433. };
  434. Vector3.prototype.scaleToRef = function (scale, result) {
  435. result.x = this.x * scale;
  436. result.y = this.y * scale;
  437. result.z = this.z * scale;
  438. };
  439. Vector3.prototype.equals = function (otherVector) {
  440. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  441. };
  442. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  443. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  444. };
  445. Vector3.prototype.equalsToFloats = function (x, y, z) {
  446. return this.x === x && this.y === y && this.z === z;
  447. };
  448. Vector3.prototype.multiplyInPlace = function (otherVector) {
  449. this.x *= otherVector.x;
  450. this.y *= otherVector.y;
  451. this.z *= otherVector.z;
  452. };
  453. Vector3.prototype.multiply = function (otherVector) {
  454. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  455. };
  456. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  457. result.x = this.x * otherVector.x;
  458. result.y = this.y * otherVector.y;
  459. result.z = this.z * otherVector.z;
  460. };
  461. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  462. return new Vector3(this.x * x, this.y * y, this.z * z);
  463. };
  464. Vector3.prototype.divide = function (otherVector) {
  465. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  466. };
  467. Vector3.prototype.divideToRef = function (otherVector, result) {
  468. result.x = this.x / otherVector.x;
  469. result.y = this.y / otherVector.y;
  470. result.z = this.z / otherVector.z;
  471. };
  472. Vector3.prototype.MinimizeInPlace = function (other) {
  473. if (other.x < this.x)
  474. this.x = other.x;
  475. if (other.y < this.y)
  476. this.y = other.y;
  477. if (other.z < this.z)
  478. this.z = other.z;
  479. };
  480. Vector3.prototype.MaximizeInPlace = function (other) {
  481. if (other.x > this.x)
  482. this.x = other.x;
  483. if (other.y > this.y)
  484. this.y = other.y;
  485. if (other.z > this.z)
  486. this.z = other.z;
  487. };
  488. Vector3.prototype.length = function () {
  489. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  490. };
  491. Vector3.prototype.lengthSquared = function () {
  492. return (this.x * this.x + this.y * this.y + this.z * this.z);
  493. };
  494. Vector3.prototype.normalize = function () {
  495. var len = this.length();
  496. if (len === 0)
  497. return;
  498. var num = 1.0 / len;
  499. this.x *= num;
  500. this.y *= num;
  501. this.z *= num;
  502. };
  503. Vector3.prototype.clone = function () {
  504. return new Vector3(this.x, this.y, this.z);
  505. };
  506. Vector3.prototype.copyFrom = function (source) {
  507. this.x = source.x;
  508. this.y = source.y;
  509. this.z = source.z;
  510. };
  511. Vector3.prototype.copyFromFloats = function (x, y, z) {
  512. this.x = x;
  513. this.y = y;
  514. this.z = z;
  515. };
  516. Vector3.FromArray = function (array, offset) {
  517. if (!offset) {
  518. offset = 0;
  519. }
  520. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  521. };
  522. Vector3.FromArrayToRef = function (array, offset, result) {
  523. result.x = array[offset];
  524. result.y = array[offset + 1];
  525. result.z = array[offset + 2];
  526. };
  527. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  528. result.x = array[offset];
  529. result.y = array[offset + 1];
  530. result.z = array[offset + 2];
  531. };
  532. Vector3.FromFloatsToRef = function (x, y, z, result) {
  533. result.x = x;
  534. result.y = y;
  535. result.z = z;
  536. };
  537. Vector3.Zero = function () {
  538. return new Vector3(0, 0, 0);
  539. };
  540. Vector3.Up = function () {
  541. return new Vector3(0, 1.0, 0);
  542. };
  543. Vector3.TransformCoordinates = function (vector, transformation) {
  544. var result = Vector3.Zero();
  545. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  546. return result;
  547. };
  548. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  552. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  553. result.x = x / w;
  554. result.y = y / w;
  555. result.z = z / w;
  556. };
  557. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  558. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  559. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  560. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  561. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  562. result.x = rx / rw;
  563. result.y = ry / rw;
  564. result.z = rz / rw;
  565. };
  566. Vector3.TransformNormal = function (vector, transformation) {
  567. var result = Vector3.Zero();
  568. Vector3.TransformNormalToRef(vector, transformation, result);
  569. return result;
  570. };
  571. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  572. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  573. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  574. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  575. };
  576. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  577. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  578. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  579. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  580. };
  581. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  582. var squared = amount * amount;
  583. var cubed = amount * squared;
  584. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  586. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  587. return new Vector3(x, y, z);
  588. };
  589. Vector3.Clamp = function (value, min, max) {
  590. var x = value.x;
  591. x = (x > max.x) ? max.x : x;
  592. x = (x < min.x) ? min.x : x;
  593. var y = value.y;
  594. y = (y > max.y) ? max.y : y;
  595. y = (y < min.y) ? min.y : y;
  596. var z = value.z;
  597. z = (z > max.z) ? max.z : z;
  598. z = (z < min.z) ? min.z : z;
  599. return new Vector3(x, y, z);
  600. };
  601. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  602. var squared = amount * amount;
  603. var cubed = amount * squared;
  604. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  605. var part2 = (-2.0 * cubed) + (3.0 * squared);
  606. var part3 = (cubed - (2.0 * squared)) + amount;
  607. var part4 = cubed - squared;
  608. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  609. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  610. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  611. return new Vector3(x, y, z);
  612. };
  613. Vector3.Lerp = function (start, end, amount) {
  614. var x = start.x + ((end.x - start.x) * amount);
  615. var y = start.y + ((end.y - start.y) * amount);
  616. var z = start.z + ((end.z - start.z) * amount);
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Dot = function (left, right) {
  620. return (left.x * right.x + left.y * right.y + left.z * right.z);
  621. };
  622. Vector3.Cross = function (left, right) {
  623. var result = Vector3.Zero();
  624. Vector3.CrossToRef(left, right, result);
  625. return result;
  626. };
  627. Vector3.CrossToRef = function (left, right, result) {
  628. result.x = left.y * right.z - left.z * right.y;
  629. result.y = left.z * right.x - left.x * right.z;
  630. result.z = left.x * right.y - left.y * right.x;
  631. };
  632. Vector3.Normalize = function (vector) {
  633. var result = Vector3.Zero();
  634. Vector3.NormalizeToRef(vector, result);
  635. return result;
  636. };
  637. Vector3.NormalizeToRef = function (vector, result) {
  638. result.copyFrom(vector);
  639. result.normalize();
  640. };
  641. Vector3.Project = function (vector, world, transform, viewport) {
  642. var cw = viewport.width;
  643. var ch = viewport.height;
  644. var cx = viewport.x;
  645. var cy = viewport.y;
  646. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  647. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  648. return Vector3.TransformCoordinates(vector, finalMatrix);
  649. };
  650. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  651. var matrix = world.multiply(view).multiply(projection);
  652. matrix.invert();
  653. source.x = source.x / viewportWidth * 2 - 1;
  654. source.y = -(source.y / viewportHeight * 2 - 1);
  655. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  656. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  657. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  658. vector = vector.scale(1.0 / num);
  659. }
  660. return vector;
  661. };
  662. Vector3.Minimize = function (left, right) {
  663. var min = left.clone();
  664. min.MinimizeInPlace(right);
  665. return min;
  666. };
  667. Vector3.Maximize = function (left, right) {
  668. var max = left.clone();
  669. max.MaximizeInPlace(right);
  670. return max;
  671. };
  672. Vector3.Distance = function (value1, value2) {
  673. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  674. };
  675. Vector3.DistanceSquared = function (value1, value2) {
  676. var x = value1.x - value2.x;
  677. var y = value1.y - value2.y;
  678. var z = value1.z - value2.z;
  679. return (x * x) + (y * y) + (z * z);
  680. };
  681. Vector3.Center = function (value1, value2) {
  682. var center = value1.add(value2);
  683. center.scaleInPlace(0.5);
  684. return center;
  685. };
  686. return Vector3;
  687. })();
  688. BABYLON.Vector3 = Vector3;
  689. var Quaternion = (function () {
  690. function Quaternion(x, y, z, w) {
  691. if (typeof x === "undefined") { x = 0; }
  692. if (typeof y === "undefined") { y = 0; }
  693. if (typeof z === "undefined") { z = 0; }
  694. if (typeof w === "undefined") { w = 1; }
  695. this.x = x;
  696. this.y = y;
  697. this.z = z;
  698. this.w = w;
  699. }
  700. Quaternion.prototype.toString = function () {
  701. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  702. };
  703. Quaternion.prototype.asArray = function () {
  704. return [this.x, this.y, this.z, this.w];
  705. };
  706. Quaternion.prototype.equals = function (otherQuaternion) {
  707. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  708. };
  709. Quaternion.prototype.clone = function () {
  710. return new Quaternion(this.x, this.y, this.z, this.w);
  711. };
  712. Quaternion.prototype.copyFrom = function (other) {
  713. this.x = other.x;
  714. this.y = other.y;
  715. this.z = other.z;
  716. this.w = other.w;
  717. };
  718. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  719. this.x = x;
  720. this.y = y;
  721. this.z = z;
  722. this.w = w;
  723. };
  724. Quaternion.prototype.add = function (other) {
  725. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  726. };
  727. Quaternion.prototype.subtract = function (other) {
  728. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  729. };
  730. Quaternion.prototype.scale = function (value) {
  731. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  732. };
  733. Quaternion.prototype.multiply = function (q1) {
  734. var result = new Quaternion(0, 0, 0, 1.0);
  735. this.multiplyToRef(q1, result);
  736. return result;
  737. };
  738. Quaternion.prototype.multiplyToRef = function (q1, result) {
  739. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  740. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  741. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  742. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  743. };
  744. Quaternion.prototype.length = function () {
  745. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  746. };
  747. Quaternion.prototype.normalize = function () {
  748. var length = 1.0 / this.length();
  749. this.x *= length;
  750. this.y *= length;
  751. this.z *= length;
  752. this.w *= length;
  753. };
  754. Quaternion.prototype.toEulerAngles = function () {
  755. var result = Vector3.Zero();
  756. this.toEulerAnglesToRef(result);
  757. return result;
  758. };
  759. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  760. var qx = this.x;
  761. var qy = this.y;
  762. var qz = this.z;
  763. var qw = this.w;
  764. var sqx = qx * qx;
  765. var sqy = qy * qy;
  766. var sqz = qz * qz;
  767. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  768. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  769. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  770. var gimbaLockTest = qx * qy + qz * qw;
  771. if (gimbaLockTest > 0.499) {
  772. yaw = 2.0 * Math.atan2(qx, qw);
  773. roll = 0;
  774. } else if (gimbaLockTest < -0.499) {
  775. yaw = -2.0 * Math.atan2(qx, qw);
  776. roll = 0;
  777. }
  778. result.x = pitch;
  779. result.y = yaw;
  780. result.z = roll;
  781. };
  782. Quaternion.prototype.toRotationMatrix = function (result) {
  783. var xx = this.x * this.x;
  784. var yy = this.y * this.y;
  785. var zz = this.z * this.z;
  786. var xy = this.x * this.y;
  787. var zw = this.z * this.w;
  788. var zx = this.z * this.x;
  789. var yw = this.y * this.w;
  790. var yz = this.y * this.z;
  791. var xw = this.x * this.w;
  792. result.m[0] = 1.0 - (2.0 * (yy + zz));
  793. result.m[1] = 2.0 * (xy + zw);
  794. result.m[2] = 2.0 * (zx - yw);
  795. result.m[3] = 0;
  796. result.m[4] = 2.0 * (xy - zw);
  797. result.m[5] = 1.0 - (2.0 * (zz + xx));
  798. result.m[6] = 2.0 * (yz + xw);
  799. result.m[7] = 0;
  800. result.m[8] = 2.0 * (zx + yw);
  801. result.m[9] = 2.0 * (yz - xw);
  802. result.m[10] = 1.0 - (2.0 * (yy + xx));
  803. result.m[11] = 0;
  804. result.m[12] = 0;
  805. result.m[13] = 0;
  806. result.m[14] = 0;
  807. result.m[15] = 1.0;
  808. };
  809. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  810. var data = matrix.m;
  811. var m11 = data[0], m12 = data[4], m13 = data[8];
  812. var m21 = data[1], m22 = data[5], m23 = data[9];
  813. var m31 = data[2], m32 = data[6], m33 = data[10];
  814. var trace = m11 + m22 + m33;
  815. var s;
  816. if (trace > 0) {
  817. s = 0.5 / Math.sqrt(trace + 1.0);
  818. this.w = 0.25 / s;
  819. this.x = (m32 - m23) * s;
  820. this.y = (m13 - m31) * s;
  821. this.z = (m21 - m12) * s;
  822. return;
  823. }
  824. if (m11 > m22 && m11 > m33) {
  825. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  826. this.w = (m32 - m23) / s;
  827. this.x = 0.25 * s;
  828. this.y = (m12 + m21) / s;
  829. this.z = (m13 + m31) / s;
  830. return;
  831. }
  832. if (m22 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  834. this.w = (m13 - m31) / s;
  835. this.x = (m12 + m21) / s;
  836. this.y = 0.25 * s;
  837. this.z = (m23 + m32) / s;
  838. return;
  839. }
  840. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  841. this.w = (m21 - m12) / s;
  842. this.x = (m13 + m31) / s;
  843. this.y = (m23 + m32) / s;
  844. this.z = 0.25 * s;
  845. };
  846. Quaternion.Inverse = function (q) {
  847. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  848. };
  849. Quaternion.RotationAxis = function (axis, angle) {
  850. var result = new Quaternion();
  851. var sin = Math.sin(angle / 2);
  852. result.w = Math.cos(angle / 2);
  853. result.x = axis.x * sin;
  854. result.y = axis.y * sin;
  855. result.z = axis.z * sin;
  856. return result;
  857. };
  858. Quaternion.FromArray = function (array, offset) {
  859. if (!offset) {
  860. offset = 0;
  861. }
  862. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  863. };
  864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  865. var result = new Quaternion();
  866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  867. return result;
  868. };
  869. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  870. var halfRoll = roll * 0.5;
  871. var halfPitch = pitch * 0.5;
  872. var halfYaw = yaw * 0.5;
  873. var sinRoll = Math.sin(halfRoll);
  874. var cosRoll = Math.cos(halfRoll);
  875. var sinPitch = Math.sin(halfPitch);
  876. var cosPitch = Math.cos(halfPitch);
  877. var sinYaw = Math.sin(halfYaw);
  878. var cosYaw = Math.cos(halfYaw);
  879. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  880. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  881. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  882. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  883. };
  884. Quaternion.Slerp = function (left, right, amount) {
  885. var num2;
  886. var num3;
  887. var num = amount;
  888. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  889. var flag = false;
  890. if (num4 < 0) {
  891. flag = true;
  892. num4 = -num4;
  893. }
  894. if (num4 > 0.999999) {
  895. num3 = 1 - num;
  896. num2 = flag ? -num : num;
  897. } else {
  898. var num5 = Math.acos(num4);
  899. var num6 = (1.0 / Math.sin(num5));
  900. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  901. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  902. }
  903. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  904. };
  905. return Quaternion;
  906. })();
  907. BABYLON.Quaternion = Quaternion;
  908. var Matrix = (function () {
  909. function Matrix() {
  910. this.m = new Float32Array(16);
  911. }
  912. Matrix.prototype.isIdentity = function () {
  913. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  914. return false;
  915. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  916. return false;
  917. return true;
  918. };
  919. Matrix.prototype.determinant = function () {
  920. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  921. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  922. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  923. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  924. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  925. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  926. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  927. };
  928. Matrix.prototype.toArray = function () {
  929. return this.m;
  930. };
  931. Matrix.prototype.asArray = function () {
  932. return this.toArray();
  933. };
  934. Matrix.prototype.invert = function () {
  935. this.invertToRef(this);
  936. };
  937. Matrix.prototype.invertToRef = function (other) {
  938. var l1 = this.m[0];
  939. var l2 = this.m[1];
  940. var l3 = this.m[2];
  941. var l4 = this.m[3];
  942. var l5 = this.m[4];
  943. var l6 = this.m[5];
  944. var l7 = this.m[6];
  945. var l8 = this.m[7];
  946. var l9 = this.m[8];
  947. var l10 = this.m[9];
  948. var l11 = this.m[10];
  949. var l12 = this.m[11];
  950. var l13 = this.m[12];
  951. var l14 = this.m[13];
  952. var l15 = this.m[14];
  953. var l16 = this.m[15];
  954. var l17 = (l11 * l16) - (l12 * l15);
  955. var l18 = (l10 * l16) - (l12 * l14);
  956. var l19 = (l10 * l15) - (l11 * l14);
  957. var l20 = (l9 * l16) - (l12 * l13);
  958. var l21 = (l9 * l15) - (l11 * l13);
  959. var l22 = (l9 * l14) - (l10 * l13);
  960. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  961. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  962. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  963. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  964. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  965. var l28 = (l7 * l16) - (l8 * l15);
  966. var l29 = (l6 * l16) - (l8 * l14);
  967. var l30 = (l6 * l15) - (l7 * l14);
  968. var l31 = (l5 * l16) - (l8 * l13);
  969. var l32 = (l5 * l15) - (l7 * l13);
  970. var l33 = (l5 * l14) - (l6 * l13);
  971. var l34 = (l7 * l12) - (l8 * l11);
  972. var l35 = (l6 * l12) - (l8 * l10);
  973. var l36 = (l6 * l11) - (l7 * l10);
  974. var l37 = (l5 * l12) - (l8 * l9);
  975. var l38 = (l5 * l11) - (l7 * l9);
  976. var l39 = (l5 * l10) - (l6 * l9);
  977. other.m[0] = l23 * l27;
  978. other.m[4] = l24 * l27;
  979. other.m[8] = l25 * l27;
  980. other.m[12] = l26 * l27;
  981. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  982. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  983. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  984. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  985. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  986. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  987. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  988. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  989. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  990. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  991. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  992. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  993. };
  994. Matrix.prototype.setTranslation = function (vector3) {
  995. this.m[12] = vector3.x;
  996. this.m[13] = vector3.y;
  997. this.m[14] = vector3.z;
  998. };
  999. Matrix.prototype.multiply = function (other) {
  1000. var result = new Matrix();
  1001. this.multiplyToRef(other, result);
  1002. return result;
  1003. };
  1004. Matrix.prototype.copyFrom = function (other) {
  1005. for (var index = 0; index < 16; index++) {
  1006. this.m[index] = other.m[index];
  1007. }
  1008. };
  1009. Matrix.prototype.copyToArray = function (array, offset) {
  1010. if (typeof offset === "undefined") { offset = 0; }
  1011. for (var index = 0; index < 16; index++) {
  1012. array[offset + index] = this.m[index];
  1013. }
  1014. };
  1015. Matrix.prototype.multiplyToRef = function (other, result) {
  1016. this.multiplyToArray(other, result.m, 0);
  1017. };
  1018. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1019. var tm0 = this.m[0];
  1020. var tm1 = this.m[1];
  1021. var tm2 = this.m[2];
  1022. var tm3 = this.m[3];
  1023. var tm4 = this.m[4];
  1024. var tm5 = this.m[5];
  1025. var tm6 = this.m[6];
  1026. var tm7 = this.m[7];
  1027. var tm8 = this.m[8];
  1028. var tm9 = this.m[9];
  1029. var tm10 = this.m[10];
  1030. var tm11 = this.m[11];
  1031. var tm12 = this.m[12];
  1032. var tm13 = this.m[13];
  1033. var tm14 = this.m[14];
  1034. var tm15 = this.m[15];
  1035. var om0 = other.m[0];
  1036. var om1 = other.m[1];
  1037. var om2 = other.m[2];
  1038. var om3 = other.m[3];
  1039. var om4 = other.m[4];
  1040. var om5 = other.m[5];
  1041. var om6 = other.m[6];
  1042. var om7 = other.m[7];
  1043. var om8 = other.m[8];
  1044. var om9 = other.m[9];
  1045. var om10 = other.m[10];
  1046. var om11 = other.m[11];
  1047. var om12 = other.m[12];
  1048. var om13 = other.m[13];
  1049. var om14 = other.m[14];
  1050. var om15 = other.m[15];
  1051. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1052. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1053. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1054. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1055. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1056. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1057. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1058. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1059. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1060. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1061. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1062. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1063. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1064. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1065. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1066. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1067. };
  1068. Matrix.prototype.equals = function (value) {
  1069. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1070. };
  1071. Matrix.prototype.clone = function () {
  1072. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1073. };
  1074. Matrix.FromArray = function (array, offset) {
  1075. var result = new Matrix();
  1076. if (!offset) {
  1077. offset = 0;
  1078. }
  1079. Matrix.FromArrayToRef(array, offset, result);
  1080. return result;
  1081. };
  1082. Matrix.FromArrayToRef = function (array, offset, result) {
  1083. for (var index = 0; index < 16; index++) {
  1084. result.m[index] = array[index + offset];
  1085. }
  1086. };
  1087. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1088. result.m[0] = initialM11;
  1089. result.m[1] = initialM12;
  1090. result.m[2] = initialM13;
  1091. result.m[3] = initialM14;
  1092. result.m[4] = initialM21;
  1093. result.m[5] = initialM22;
  1094. result.m[6] = initialM23;
  1095. result.m[7] = initialM24;
  1096. result.m[8] = initialM31;
  1097. result.m[9] = initialM32;
  1098. result.m[10] = initialM33;
  1099. result.m[11] = initialM34;
  1100. result.m[12] = initialM41;
  1101. result.m[13] = initialM42;
  1102. result.m[14] = initialM43;
  1103. result.m[15] = initialM44;
  1104. };
  1105. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1106. var result = new Matrix();
  1107. result.m[0] = initialM11;
  1108. result.m[1] = initialM12;
  1109. result.m[2] = initialM13;
  1110. result.m[3] = initialM14;
  1111. result.m[4] = initialM21;
  1112. result.m[5] = initialM22;
  1113. result.m[6] = initialM23;
  1114. result.m[7] = initialM24;
  1115. result.m[8] = initialM31;
  1116. result.m[9] = initialM32;
  1117. result.m[10] = initialM33;
  1118. result.m[11] = initialM34;
  1119. result.m[12] = initialM41;
  1120. result.m[13] = initialM42;
  1121. result.m[14] = initialM43;
  1122. result.m[15] = initialM44;
  1123. return result;
  1124. };
  1125. Matrix.Identity = function () {
  1126. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1127. };
  1128. Matrix.IdentityToRef = function (result) {
  1129. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1130. };
  1131. Matrix.Zero = function () {
  1132. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1133. };
  1134. Matrix.RotationX = function (angle) {
  1135. var result = new Matrix();
  1136. Matrix.RotationXToRef(angle, result);
  1137. return result;
  1138. };
  1139. Matrix.RotationXToRef = function (angle, result) {
  1140. var s = Math.sin(angle);
  1141. var c = Math.cos(angle);
  1142. result.m[0] = 1.0;
  1143. result.m[15] = 1.0;
  1144. result.m[5] = c;
  1145. result.m[10] = c;
  1146. result.m[9] = -s;
  1147. result.m[6] = s;
  1148. result.m[1] = 0;
  1149. result.m[2] = 0;
  1150. result.m[3] = 0;
  1151. result.m[4] = 0;
  1152. result.m[7] = 0;
  1153. result.m[8] = 0;
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. };
  1159. Matrix.RotationY = function (angle) {
  1160. var result = new Matrix();
  1161. Matrix.RotationYToRef(angle, result);
  1162. return result;
  1163. };
  1164. Matrix.RotationYToRef = function (angle, result) {
  1165. var s = Math.sin(angle);
  1166. var c = Math.cos(angle);
  1167. result.m[5] = 1.0;
  1168. result.m[15] = 1.0;
  1169. result.m[0] = c;
  1170. result.m[2] = -s;
  1171. result.m[8] = s;
  1172. result.m[10] = c;
  1173. result.m[1] = 0;
  1174. result.m[3] = 0;
  1175. result.m[4] = 0;
  1176. result.m[6] = 0;
  1177. result.m[7] = 0;
  1178. result.m[9] = 0;
  1179. result.m[11] = 0;
  1180. result.m[12] = 0;
  1181. result.m[13] = 0;
  1182. result.m[14] = 0;
  1183. };
  1184. Matrix.RotationZ = function (angle) {
  1185. var result = new Matrix();
  1186. Matrix.RotationZToRef(angle, result);
  1187. return result;
  1188. };
  1189. Matrix.RotationZToRef = function (angle, result) {
  1190. var s = Math.sin(angle);
  1191. var c = Math.cos(angle);
  1192. result.m[10] = 1.0;
  1193. result.m[15] = 1.0;
  1194. result.m[0] = c;
  1195. result.m[1] = s;
  1196. result.m[4] = -s;
  1197. result.m[5] = c;
  1198. result.m[2] = 0;
  1199. result.m[3] = 0;
  1200. result.m[6] = 0;
  1201. result.m[7] = 0;
  1202. result.m[8] = 0;
  1203. result.m[9] = 0;
  1204. result.m[11] = 0;
  1205. result.m[12] = 0;
  1206. result.m[13] = 0;
  1207. result.m[14] = 0;
  1208. };
  1209. Matrix.RotationAxis = function (axis, angle) {
  1210. var s = Math.sin(-angle);
  1211. var c = Math.cos(-angle);
  1212. var c1 = 1 - c;
  1213. axis.normalize();
  1214. var result = Matrix.Zero();
  1215. result.m[0] = (axis.x * axis.x) * c1 + c;
  1216. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1217. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1218. result.m[3] = 0.0;
  1219. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1220. result.m[5] = (axis.y * axis.y) * c1 + c;
  1221. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1222. result.m[7] = 0.0;
  1223. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1224. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1225. result.m[10] = (axis.z * axis.z) * c1 + c;
  1226. result.m[11] = 0.0;
  1227. result.m[15] = 1.0;
  1228. return result;
  1229. };
  1230. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1231. var result = new Matrix();
  1232. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1233. return result;
  1234. };
  1235. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1236. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1237. this._tempQuaternion.toRotationMatrix(result);
  1238. };
  1239. Matrix.Scaling = function (x, y, z) {
  1240. var result = Matrix.Zero();
  1241. Matrix.ScalingToRef(x, y, z, result);
  1242. return result;
  1243. };
  1244. Matrix.ScalingToRef = function (x, y, z, result) {
  1245. result.m[0] = x;
  1246. result.m[1] = 0;
  1247. result.m[2] = 0;
  1248. result.m[3] = 0;
  1249. result.m[4] = 0;
  1250. result.m[5] = y;
  1251. result.m[6] = 0;
  1252. result.m[7] = 0;
  1253. result.m[8] = 0;
  1254. result.m[9] = 0;
  1255. result.m[10] = z;
  1256. result.m[11] = 0;
  1257. result.m[12] = 0;
  1258. result.m[13] = 0;
  1259. result.m[14] = 0;
  1260. result.m[15] = 1.0;
  1261. };
  1262. Matrix.Translation = function (x, y, z) {
  1263. var result = Matrix.Identity();
  1264. Matrix.TranslationToRef(x, y, z, result);
  1265. return result;
  1266. };
  1267. Matrix.TranslationToRef = function (x, y, z, result) {
  1268. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1269. };
  1270. Matrix.LookAtLH = function (eye, target, up) {
  1271. var result = Matrix.Zero();
  1272. Matrix.LookAtLHToRef(eye, target, up, result);
  1273. return result;
  1274. };
  1275. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1276. target.subtractToRef(eye, this._zAxis);
  1277. this._zAxis.normalize();
  1278. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1279. this._xAxis.normalize();
  1280. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1281. this._yAxis.normalize();
  1282. var ex = -Vector3.Dot(this._xAxis, eye);
  1283. var ey = -Vector3.Dot(this._yAxis, eye);
  1284. var ez = -Vector3.Dot(this._zAxis, eye);
  1285. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1286. };
  1287. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1288. var hw = 2.0 / width;
  1289. var hh = 2.0 / height;
  1290. var id = 1.0 / (zfar - znear);
  1291. var nid = znear / (znear - zfar);
  1292. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1293. };
  1294. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1295. var matrix = Matrix.Zero();
  1296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1297. return matrix;
  1298. };
  1299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1300. result.m[0] = 2.0 / (right - left);
  1301. result.m[1] = result.m[2] = result.m[3] = 0;
  1302. result.m[5] = 2.0 / (top - bottom);
  1303. result.m[4] = result.m[6] = result.m[7] = 0;
  1304. result.m[10] = -1.0 / (znear - zfar);
  1305. result.m[8] = result.m[9] = result.m[11] = 0;
  1306. result.m[12] = (left + right) / (left - right);
  1307. result.m[13] = (top + bottom) / (bottom - top);
  1308. result.m[14] = znear / (znear - zfar);
  1309. result.m[15] = 1.0;
  1310. };
  1311. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1312. var matrix = Matrix.Zero();
  1313. matrix.m[0] = (2.0 * znear) / width;
  1314. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1315. matrix.m[5] = (2.0 * znear) / height;
  1316. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1317. matrix.m[10] = -zfar / (znear - zfar);
  1318. matrix.m[8] = matrix.m[9] = 0.0;
  1319. matrix.m[11] = 1.0;
  1320. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1321. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1322. return matrix;
  1323. };
  1324. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1325. var matrix = Matrix.Zero();
  1326. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1327. return matrix;
  1328. };
  1329. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1330. var tan = 1.0 / (Math.tan(fov * 0.5));
  1331. result.m[0] = tan / aspect;
  1332. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1333. result.m[5] = tan;
  1334. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1335. result.m[8] = result.m[9] = 0.0;
  1336. result.m[10] = -zfar / (znear - zfar);
  1337. result.m[11] = 1.0;
  1338. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1339. result.m[14] = (znear * zfar) / (znear - zfar);
  1340. };
  1341. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1342. var cw = viewport.width;
  1343. var ch = viewport.height;
  1344. var cx = viewport.x;
  1345. var cy = viewport.y;
  1346. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1347. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1348. };
  1349. Matrix.Transpose = function (matrix) {
  1350. var result = new Matrix();
  1351. result.m[0] = matrix.m[0];
  1352. result.m[1] = matrix.m[4];
  1353. result.m[2] = matrix.m[8];
  1354. result.m[3] = matrix.m[12];
  1355. result.m[4] = matrix.m[1];
  1356. result.m[5] = matrix.m[5];
  1357. result.m[6] = matrix.m[9];
  1358. result.m[7] = matrix.m[13];
  1359. result.m[8] = matrix.m[2];
  1360. result.m[9] = matrix.m[6];
  1361. result.m[10] = matrix.m[10];
  1362. result.m[11] = matrix.m[14];
  1363. result.m[12] = matrix.m[3];
  1364. result.m[13] = matrix.m[7];
  1365. result.m[14] = matrix.m[11];
  1366. result.m[15] = matrix.m[15];
  1367. return result;
  1368. };
  1369. Matrix.Reflection = function (plane) {
  1370. var matrix = new Matrix();
  1371. Matrix.ReflectionToRef(plane, matrix);
  1372. return matrix;
  1373. };
  1374. Matrix.ReflectionToRef = function (plane, result) {
  1375. plane.normalize();
  1376. var x = plane.normal.x;
  1377. var y = plane.normal.y;
  1378. var z = plane.normal.z;
  1379. var temp = -2 * x;
  1380. var temp2 = -2 * y;
  1381. var temp3 = -2 * z;
  1382. result.m[0] = (temp * x) + 1;
  1383. result.m[1] = temp2 * x;
  1384. result.m[2] = temp3 * x;
  1385. result.m[3] = 0.0;
  1386. result.m[4] = temp * y;
  1387. result.m[5] = (temp2 * y) + 1;
  1388. result.m[6] = temp3 * y;
  1389. result.m[7] = 0.0;
  1390. result.m[8] = temp * z;
  1391. result.m[9] = temp2 * z;
  1392. result.m[10] = (temp3 * z) + 1;
  1393. result.m[11] = 0.0;
  1394. result.m[12] = temp * plane.d;
  1395. result.m[13] = temp2 * plane.d;
  1396. result.m[14] = temp3 * plane.d;
  1397. result.m[15] = 1.0;
  1398. };
  1399. Matrix._tempQuaternion = new Quaternion();
  1400. Matrix._xAxis = Vector3.Zero();
  1401. Matrix._yAxis = Vector3.Zero();
  1402. Matrix._zAxis = Vector3.Zero();
  1403. return Matrix;
  1404. })();
  1405. BABYLON.Matrix = Matrix;
  1406. var Plane = (function () {
  1407. function Plane(a, b, c, d) {
  1408. this.normal = new Vector3(a, b, c);
  1409. this.d = d;
  1410. }
  1411. Plane.prototype.asArray = function () {
  1412. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1413. };
  1414. Plane.prototype.clone = function () {
  1415. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1416. };
  1417. Plane.prototype.normalize = function () {
  1418. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1419. var magnitude = 0;
  1420. if (norm != 0) {
  1421. magnitude = 1.0 / norm;
  1422. }
  1423. this.normal.x *= magnitude;
  1424. this.normal.y *= magnitude;
  1425. this.normal.z *= magnitude;
  1426. this.d *= magnitude;
  1427. };
  1428. Plane.prototype.transform = function (transformation) {
  1429. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1430. var x = this.normal.x;
  1431. var y = this.normal.y;
  1432. var z = this.normal.z;
  1433. var d = this.d;
  1434. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1435. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1436. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1437. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1438. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1439. };
  1440. Plane.prototype.dotCoordinate = function (point) {
  1441. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1442. };
  1443. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1444. var x1 = point2.x - point1.x;
  1445. var y1 = point2.y - point1.y;
  1446. var z1 = point2.z - point1.z;
  1447. var x2 = point3.x - point1.x;
  1448. var y2 = point3.y - point1.y;
  1449. var z2 = point3.z - point1.z;
  1450. var yz = (y1 * z2) - (z1 * y2);
  1451. var xz = (z1 * x2) - (x1 * z2);
  1452. var xy = (x1 * y2) - (y1 * x2);
  1453. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1454. var invPyth;
  1455. if (pyth != 0) {
  1456. invPyth = 1.0 / pyth;
  1457. } else {
  1458. invPyth = 0;
  1459. }
  1460. this.normal.x = yz * invPyth;
  1461. this.normal.y = xz * invPyth;
  1462. this.normal.z = xy * invPyth;
  1463. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1464. };
  1465. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1466. var dot = Vector3.Dot(this.normal, direction);
  1467. return (dot <= epsilon);
  1468. };
  1469. Plane.prototype.signedDistanceTo = function (point) {
  1470. return Vector3.Dot(point, this.normal) + this.d;
  1471. };
  1472. Plane.FromArray = function (array) {
  1473. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1474. };
  1475. Plane.FromPoints = function (point1, point2, point3) {
  1476. var result = new BABYLON.Plane(0, 0, 0, 0);
  1477. result.copyFromPoints(point1, point2, point3);
  1478. return result;
  1479. };
  1480. Plane.FromPositionAndNormal = function (origin, normal) {
  1481. var result = new BABYLON.Plane(0, 0, 0, 0);
  1482. normal.normalize();
  1483. result.normal = normal;
  1484. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1485. return result;
  1486. };
  1487. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1488. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1489. return Vector3.Dot(point, normal) + d;
  1490. };
  1491. return Plane;
  1492. })();
  1493. BABYLON.Plane = Plane;
  1494. var Viewport = (function () {
  1495. function Viewport(x, y, width, height) {
  1496. this.x = x;
  1497. this.y = y;
  1498. this.width = width;
  1499. this.height = height;
  1500. }
  1501. Viewport.prototype.toGlobal = function (engine) {
  1502. var width = engine.getRenderWidth();
  1503. var height = engine.getRenderHeight();
  1504. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1505. };
  1506. return Viewport;
  1507. })();
  1508. BABYLON.Viewport = Viewport;
  1509. var Frustum = (function () {
  1510. function Frustum() {
  1511. }
  1512. Frustum.GetPlanes = function (transform) {
  1513. var frustumPlanes = [];
  1514. for (var index = 0; index < 6; index++) {
  1515. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1516. }
  1517. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1518. return frustumPlanes;
  1519. };
  1520. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1521. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1522. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1523. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1524. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1525. frustumPlanes[0].normalize();
  1526. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1527. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1528. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1529. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1530. frustumPlanes[1].normalize();
  1531. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1532. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1533. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1534. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1535. frustumPlanes[2].normalize();
  1536. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1537. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1538. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1539. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1540. frustumPlanes[3].normalize();
  1541. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1542. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1543. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1544. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1545. frustumPlanes[4].normalize();
  1546. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1547. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1548. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1549. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1550. frustumPlanes[5].normalize();
  1551. };
  1552. return Frustum;
  1553. })();
  1554. BABYLON.Frustum = Frustum;
  1555. var Ray = (function () {
  1556. function Ray(origin, direction) {
  1557. this.origin = origin;
  1558. this.direction = direction;
  1559. }
  1560. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1561. var d = 0.0;
  1562. var maxValue = Number.MAX_VALUE;
  1563. if (Math.abs(this.direction.x) < 0.0000001) {
  1564. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1565. return false;
  1566. }
  1567. } else {
  1568. var inv = 1.0 / this.direction.x;
  1569. var min = (minimum.x - this.origin.x) * inv;
  1570. var max = (maximum.x - this.origin.x) * inv;
  1571. if (min > max) {
  1572. var temp = min;
  1573. min = max;
  1574. max = temp;
  1575. }
  1576. d = Math.max(min, d);
  1577. maxValue = Math.min(max, maxValue);
  1578. if (d > maxValue) {
  1579. return false;
  1580. }
  1581. }
  1582. if (Math.abs(this.direction.y) < 0.0000001) {
  1583. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1584. return false;
  1585. }
  1586. } else {
  1587. inv = 1.0 / this.direction.y;
  1588. min = (minimum.y - this.origin.y) * inv;
  1589. max = (maximum.y - this.origin.y) * inv;
  1590. if (min > max) {
  1591. temp = min;
  1592. min = max;
  1593. max = temp;
  1594. }
  1595. d = Math.max(min, d);
  1596. maxValue = Math.min(max, maxValue);
  1597. if (d > maxValue) {
  1598. return false;
  1599. }
  1600. }
  1601. if (Math.abs(this.direction.z) < 0.0000001) {
  1602. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1603. return false;
  1604. }
  1605. } else {
  1606. inv = 1.0 / this.direction.z;
  1607. min = (minimum.z - this.origin.z) * inv;
  1608. max = (maximum.z - this.origin.z) * inv;
  1609. if (min > max) {
  1610. temp = min;
  1611. min = max;
  1612. max = temp;
  1613. }
  1614. d = Math.max(min, d);
  1615. maxValue = Math.min(max, maxValue);
  1616. if (d > maxValue) {
  1617. return false;
  1618. }
  1619. }
  1620. return true;
  1621. };
  1622. Ray.prototype.intersectsBox = function (box) {
  1623. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1624. };
  1625. Ray.prototype.intersectsSphere = function (sphere) {
  1626. var x = sphere.center.x - this.origin.x;
  1627. var y = sphere.center.y - this.origin.y;
  1628. var z = sphere.center.z - this.origin.z;
  1629. var pyth = (x * x) + (y * y) + (z * z);
  1630. var rr = sphere.radius * sphere.radius;
  1631. if (pyth <= rr) {
  1632. return true;
  1633. }
  1634. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1635. if (dot < 0.0) {
  1636. return false;
  1637. }
  1638. var temp = pyth - (dot * dot);
  1639. return temp <= rr;
  1640. };
  1641. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1642. if (!this._edge1) {
  1643. this._edge1 = BABYLON.Vector3.Zero();
  1644. this._edge2 = BABYLON.Vector3.Zero();
  1645. this._pvec = BABYLON.Vector3.Zero();
  1646. this._tvec = BABYLON.Vector3.Zero();
  1647. this._qvec = BABYLON.Vector3.Zero();
  1648. }
  1649. vertex1.subtractToRef(vertex0, this._edge1);
  1650. vertex2.subtractToRef(vertex0, this._edge2);
  1651. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1652. var det = Vector3.Dot(this._edge1, this._pvec);
  1653. if (det === 0) {
  1654. return null;
  1655. }
  1656. var invdet = 1 / det;
  1657. this.origin.subtractToRef(vertex0, this._tvec);
  1658. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1659. if (bu < 0 || bu > 1.0) {
  1660. return null;
  1661. }
  1662. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1663. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1664. if (bv < 0 || bu + bv > 1.0) {
  1665. return null;
  1666. }
  1667. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1668. };
  1669. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1670. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1671. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1672. var direction = end.subtract(start);
  1673. direction.normalize();
  1674. return new Ray(start, direction);
  1675. };
  1676. Ray.Transform = function (ray, matrix) {
  1677. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1678. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1679. return new Ray(newOrigin, newDirection);
  1680. };
  1681. return Ray;
  1682. })();
  1683. BABYLON.Ray = Ray;
  1684. (function (Space) {
  1685. Space[Space["LOCAL"] = 0] = "LOCAL";
  1686. Space[Space["WORLD"] = 1] = "WORLD";
  1687. })(BABYLON.Space || (BABYLON.Space = {}));
  1688. var Space = BABYLON.Space;
  1689. var Axis = (function () {
  1690. function Axis() {
  1691. }
  1692. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1693. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1694. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1695. return Axis;
  1696. })();
  1697. BABYLON.Axis = Axis;
  1698. ;
  1699. })(BABYLON || (BABYLON = {}));
  1700. var BABYLON;
  1701. (function (BABYLON) {
  1702. var screenshotCanvas;
  1703. var fpsRange = 60;
  1704. var previousFramesDuration = [];
  1705. var fps = 60;
  1706. var deltaTime = 0;
  1707. var cloneValue = function (source, destinationObject) {
  1708. if (!source)
  1709. return null;
  1710. if (source instanceof BABYLON.Mesh) {
  1711. return null;
  1712. }
  1713. if (source instanceof BABYLON.SubMesh) {
  1714. return source.clone(destinationObject);
  1715. } else if (source.clone) {
  1716. return source.clone();
  1717. }
  1718. return null;
  1719. };
  1720. var Tools = (function () {
  1721. function Tools() {
  1722. }
  1723. Tools.GetFilename = function (path) {
  1724. var index = path.lastIndexOf("/");
  1725. if (index < 0)
  1726. return path;
  1727. return path.substring(index + 1);
  1728. };
  1729. Tools.GetDOMTextContent = function (element) {
  1730. var result = "";
  1731. var child = element.firstChild;
  1732. while (child) {
  1733. if (child.nodeType == 3) {
  1734. result += child.textContent;
  1735. }
  1736. child = child.nextSibling;
  1737. }
  1738. return result;
  1739. };
  1740. Tools.ToDegrees = function (angle) {
  1741. return angle * 180 / Math.PI;
  1742. };
  1743. Tools.ToRadians = function (angle) {
  1744. return angle * Math.PI / 180;
  1745. };
  1746. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1747. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1748. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1749. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1750. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1751. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1752. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1753. }
  1754. return {
  1755. minimum: minimum,
  1756. maximum: maximum
  1757. };
  1758. };
  1759. Tools.ExtractMinAndMax = function (positions, start, count) {
  1760. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1761. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1762. for (var index = start; index < start + count; index++) {
  1763. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1764. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1765. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1766. }
  1767. return {
  1768. minimum: minimum,
  1769. maximum: maximum
  1770. };
  1771. };
  1772. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1773. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1774. return undefined;
  1775. return Array.isArray(obj) ? obj : [obj];
  1776. };
  1777. Tools.GetPointerPrefix = function () {
  1778. var eventPrefix = "pointer";
  1779. if (!navigator.pointerEnabled) {
  1780. eventPrefix = "mouse";
  1781. }
  1782. return eventPrefix;
  1783. };
  1784. Tools.QueueNewFrame = function (func) {
  1785. if (window.requestAnimationFrame)
  1786. window.requestAnimationFrame(func);
  1787. else if (window.msRequestAnimationFrame)
  1788. window.msRequestAnimationFrame(func);
  1789. else if (window.webkitRequestAnimationFrame)
  1790. window.webkitRequestAnimationFrame(func);
  1791. else if (window.mozRequestAnimationFrame)
  1792. window.mozRequestAnimationFrame(func);
  1793. else if (window.oRequestAnimationFrame)
  1794. window.oRequestAnimationFrame(func);
  1795. else {
  1796. window.setTimeout(func, 16);
  1797. }
  1798. };
  1799. Tools.RequestFullscreen = function (element) {
  1800. if (element.requestFullscreen)
  1801. element.requestFullscreen();
  1802. else if (element.msRequestFullscreen)
  1803. element.msRequestFullscreen();
  1804. else if (element.webkitRequestFullscreen)
  1805. element.webkitRequestFullscreen();
  1806. else if (element.mozRequestFullScreen)
  1807. element.mozRequestFullScreen();
  1808. };
  1809. Tools.ExitFullscreen = function () {
  1810. if (document.exitFullscreen) {
  1811. document.exitFullscreen();
  1812. } else if (document.mozCancelFullScreen) {
  1813. document.mozCancelFullScreen();
  1814. } else if (document.webkitCancelFullScreen) {
  1815. document.webkitCancelFullScreen();
  1816. } else if (document.msCancelFullScreen) {
  1817. document.msCancelFullScreen();
  1818. }
  1819. };
  1820. Tools.CleanUrl = function (url) {
  1821. url = url.replace(/#/mg, "%23");
  1822. return url;
  1823. };
  1824. Tools.LoadImage = function (url, onload, onerror, database) {
  1825. url = Tools.CleanUrl(url);
  1826. var img = new Image();
  1827. img.crossOrigin = 'anonymous';
  1828. img.onload = function () {
  1829. onload(img);
  1830. };
  1831. img.onerror = function (err) {
  1832. onerror(img, err);
  1833. };
  1834. var noIndexedDB = function () {
  1835. img.src = url;
  1836. };
  1837. var loadFromIndexedDB = function () {
  1838. database.loadImageFromDB(url, img);
  1839. };
  1840. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1841. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1842. } else {
  1843. if (url.indexOf("file:") === -1) {
  1844. noIndexedDB();
  1845. } else {
  1846. try {
  1847. var textureName = url.substring(5);
  1848. var blobURL;
  1849. try {
  1850. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1851. } catch (ex) {
  1852. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1853. }
  1854. img.src = blobURL;
  1855. } catch (e) {
  1856. Tools.Log("Error while trying to load texture: " + textureName);
  1857. img.src = null;
  1858. }
  1859. }
  1860. }
  1861. return img;
  1862. };
  1863. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1864. url = Tools.CleanUrl(url);
  1865. var noIndexedDB = function () {
  1866. var request = new XMLHttpRequest();
  1867. var loadUrl = Tools.BaseUrl + url;
  1868. request.open('GET', loadUrl, true);
  1869. if (useArrayBuffer) {
  1870. request.responseType = "arraybuffer";
  1871. }
  1872. request.onprogress = progressCallBack;
  1873. request.onreadystatechange = function () {
  1874. if (request.readyState == 4) {
  1875. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1876. callback(!useArrayBuffer ? request.responseText : request.response);
  1877. } else {
  1878. if (onError) {
  1879. onError();
  1880. } else {
  1881. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1882. }
  1883. }
  1884. }
  1885. };
  1886. request.send(null);
  1887. };
  1888. var loadFromIndexedDB = function () {
  1889. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1890. };
  1891. if (url.indexOf("file:") !== -1) {
  1892. var fileName = url.substring(5);
  1893. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1894. } else {
  1895. if (database && database.enableSceneOffline) {
  1896. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1897. } else {
  1898. noIndexedDB();
  1899. }
  1900. }
  1901. };
  1902. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1903. var reader = new FileReader();
  1904. reader.onload = function (e) {
  1905. callback(e.target.result);
  1906. };
  1907. reader.onprogress = progressCallBack;
  1908. if (!useArrayBuffer) {
  1909. reader.readAsText(fileToLoad);
  1910. } else {
  1911. reader.readAsArrayBuffer(fileToLoad);
  1912. }
  1913. };
  1914. Tools.CheckExtends = function (v, min, max) {
  1915. if (v.x < min.x)
  1916. min.x = v.x;
  1917. if (v.y < min.y)
  1918. min.y = v.y;
  1919. if (v.z < min.z)
  1920. min.z = v.z;
  1921. if (v.x > max.x)
  1922. max.x = v.x;
  1923. if (v.y > max.y)
  1924. max.y = v.y;
  1925. if (v.z > max.z)
  1926. max.z = v.z;
  1927. };
  1928. Tools.WithinEpsilon = function (a, b) {
  1929. var num = a - b;
  1930. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1931. };
  1932. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1933. for (var prop in source) {
  1934. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1935. continue;
  1936. }
  1937. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1938. continue;
  1939. }
  1940. var sourceValue = source[prop];
  1941. var typeOfSourceValue = typeof sourceValue;
  1942. if (typeOfSourceValue == "function") {
  1943. continue;
  1944. }
  1945. if (typeOfSourceValue == "object") {
  1946. if (sourceValue instanceof Array) {
  1947. destination[prop] = [];
  1948. if (sourceValue.length > 0) {
  1949. if (typeof sourceValue[0] == "object") {
  1950. for (var index = 0; index < sourceValue.length; index++) {
  1951. var clonedValue = cloneValue(sourceValue[index], destination);
  1952. if (destination[prop].indexOf(clonedValue) === -1) {
  1953. destination[prop].push(clonedValue);
  1954. }
  1955. }
  1956. } else {
  1957. destination[prop] = sourceValue.slice(0);
  1958. }
  1959. }
  1960. } else {
  1961. destination[prop] = cloneValue(sourceValue, destination);
  1962. }
  1963. } else {
  1964. destination[prop] = sourceValue;
  1965. }
  1966. }
  1967. };
  1968. Tools.IsEmpty = function (obj) {
  1969. for (var i in obj) {
  1970. return false;
  1971. }
  1972. return true;
  1973. };
  1974. Tools.RegisterTopRootEvents = function (events) {
  1975. for (var index = 0; index < events.length; index++) {
  1976. var event = events[index];
  1977. window.addEventListener(event.name, event.handler, false);
  1978. try {
  1979. if (window.parent) {
  1980. window.parent.addEventListener(event.name, event.handler, false);
  1981. }
  1982. } catch (e) {
  1983. }
  1984. }
  1985. };
  1986. Tools.UnregisterTopRootEvents = function (events) {
  1987. for (var index = 0; index < events.length; index++) {
  1988. var event = events[index];
  1989. window.removeEventListener(event.name, event.handler);
  1990. try {
  1991. if (window.parent) {
  1992. window.parent.removeEventListener(event.name, event.handler);
  1993. }
  1994. } catch (e) {
  1995. }
  1996. }
  1997. };
  1998. Tools.GetFps = function () {
  1999. return fps;
  2000. };
  2001. Tools.GetDeltaTime = function () {
  2002. return deltaTime;
  2003. };
  2004. Tools._MeasureFps = function () {
  2005. previousFramesDuration.push((new Date).getTime());
  2006. var length = previousFramesDuration.length;
  2007. if (length >= 2) {
  2008. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2009. }
  2010. if (length >= fpsRange) {
  2011. if (length > fpsRange) {
  2012. previousFramesDuration.splice(0, 1);
  2013. length = previousFramesDuration.length;
  2014. }
  2015. var sum = 0;
  2016. for (var id = 0; id < length - 1; id++) {
  2017. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2018. }
  2019. fps = 1000.0 / (sum / (length - 1));
  2020. }
  2021. };
  2022. Tools.CreateScreenshot = function (engine, camera, size) {
  2023. var width;
  2024. var height;
  2025. var scene = camera.getScene();
  2026. var previousCamera = null;
  2027. if (scene.activeCamera !== camera) {
  2028. previousCamera = scene.activeCamera;
  2029. scene.activeCamera = camera;
  2030. }
  2031. if (size.precision) {
  2032. width = Math.round(engine.getRenderWidth() * size.precision);
  2033. height = Math.round(width / engine.getAspectRatio(camera));
  2034. size = { width: width, height: height };
  2035. } else if (size.width && size.height) {
  2036. width = size.width;
  2037. height = size.height;
  2038. } else if (size.width && !size.height) {
  2039. width = size.width;
  2040. height = Math.round(width / engine.getAspectRatio(camera));
  2041. size = { width: width, height: height };
  2042. } else if (size.height && !size.width) {
  2043. height = size.height;
  2044. width = Math.round(height * engine.getAspectRatio(camera));
  2045. size = { width: width, height: height };
  2046. } else if (!isNaN(size)) {
  2047. height = size;
  2048. width = size;
  2049. } else {
  2050. Tools.Error("Invalid 'size' parameter !");
  2051. return;
  2052. }
  2053. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2054. texture.renderList = engine.scenes[0].meshes;
  2055. texture.onAfterRender = function () {
  2056. var numberOfChannelsByLine = width * 4;
  2057. var halfHeight = height / 2;
  2058. var data = engine.readPixels(0, 0, width, height);
  2059. for (var i = 0; i < halfHeight; i++) {
  2060. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2061. var currentCell = j + i * numberOfChannelsByLine;
  2062. var targetLine = height - i - 1;
  2063. var targetCell = j + targetLine * numberOfChannelsByLine;
  2064. var temp = data[currentCell];
  2065. data[currentCell] = data[targetCell];
  2066. data[targetCell] = temp;
  2067. }
  2068. }
  2069. if (!screenshotCanvas) {
  2070. screenshotCanvas = document.createElement('canvas');
  2071. }
  2072. screenshotCanvas.width = width;
  2073. screenshotCanvas.height = height;
  2074. var context = screenshotCanvas.getContext('2d');
  2075. var imageData = context.createImageData(width, height);
  2076. imageData.data.set(data);
  2077. context.putImageData(imageData, 0, 0);
  2078. var base64Image = screenshotCanvas.toDataURL();
  2079. if (("download" in document.createElement("a"))) {
  2080. var a = window.document.createElement("a");
  2081. a.href = base64Image;
  2082. var date = new Date();
  2083. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2084. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2085. window.document.body.appendChild(a);
  2086. a.addEventListener("click", function () {
  2087. a.parentElement.removeChild(a);
  2088. });
  2089. a.click();
  2090. } else {
  2091. var newWindow = window.open("");
  2092. var img = newWindow.document.createElement("img");
  2093. img.src = base64Image;
  2094. newWindow.document.body.appendChild(img);
  2095. }
  2096. };
  2097. texture.render(true);
  2098. texture.dispose();
  2099. if (previousCamera) {
  2100. scene.activeCamera = previousCamera;
  2101. }
  2102. };
  2103. Tools.ValidateXHRData = function (xhr, dataType) {
  2104. if (typeof dataType === "undefined") { dataType = 7; }
  2105. try {
  2106. if (dataType & 1) {
  2107. if (xhr.responseText && xhr.responseText.length > 0) {
  2108. return true;
  2109. } else if (dataType === 1) {
  2110. return false;
  2111. }
  2112. }
  2113. if (dataType & 2) {
  2114. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2115. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2116. return true;
  2117. } else if (dataType === 2) {
  2118. return false;
  2119. }
  2120. }
  2121. if (dataType & 4) {
  2122. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2123. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2124. return true;
  2125. } else {
  2126. return false;
  2127. }
  2128. }
  2129. } catch (e) {
  2130. }
  2131. return false;
  2132. };
  2133. Object.defineProperty(Tools, "NoneLogLevel", {
  2134. get: function () {
  2135. return Tools._NoneLogLevel;
  2136. },
  2137. enumerable: true,
  2138. configurable: true
  2139. });
  2140. Object.defineProperty(Tools, "MessageLogLevel", {
  2141. get: function () {
  2142. return Tools._MessageLogLevel;
  2143. },
  2144. enumerable: true,
  2145. configurable: true
  2146. });
  2147. Object.defineProperty(Tools, "WarningLogLevel", {
  2148. get: function () {
  2149. return Tools._WarningLogLevel;
  2150. },
  2151. enumerable: true,
  2152. configurable: true
  2153. });
  2154. Object.defineProperty(Tools, "ErrorLogLevel", {
  2155. get: function () {
  2156. return Tools._ErrorLogLevel;
  2157. },
  2158. enumerable: true,
  2159. configurable: true
  2160. });
  2161. Object.defineProperty(Tools, "AllLogLevel", {
  2162. get: function () {
  2163. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2164. },
  2165. enumerable: true,
  2166. configurable: true
  2167. });
  2168. Tools._FormatMessage = function (message) {
  2169. var padStr = function (i) {
  2170. return (i < 10) ? "0" + i : "" + i;
  2171. };
  2172. var date = new Date();
  2173. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2174. };
  2175. Tools._LogDisabled = function (message) {
  2176. };
  2177. Tools._LogEnabled = function (message) {
  2178. console.log(Tools._FormatMessage(message));
  2179. };
  2180. Tools._WarnDisabled = function (message) {
  2181. };
  2182. Tools._WarnEnabled = function (message) {
  2183. console.warn(Tools._FormatMessage(message));
  2184. };
  2185. Tools._ErrorDisabled = function (message) {
  2186. };
  2187. Tools._ErrorEnabled = function (message) {
  2188. console.error(Tools._FormatMessage(message));
  2189. };
  2190. Object.defineProperty(Tools, "LogLevels", {
  2191. set: function (level) {
  2192. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2193. Tools.Log = Tools._LogEnabled;
  2194. } else {
  2195. Tools.Log = Tools._LogDisabled;
  2196. }
  2197. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2198. Tools.Warn = Tools._WarnEnabled;
  2199. } else {
  2200. Tools.Warn = Tools._WarnDisabled;
  2201. }
  2202. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2203. Tools.Error = Tools._ErrorEnabled;
  2204. } else {
  2205. Tools.Error = Tools._ErrorDisabled;
  2206. }
  2207. },
  2208. enumerable: true,
  2209. configurable: true
  2210. });
  2211. Tools.BaseUrl = "";
  2212. Tools._NoneLogLevel = 0;
  2213. Tools._MessageLogLevel = 1;
  2214. Tools._WarningLogLevel = 2;
  2215. Tools._ErrorLogLevel = 4;
  2216. Tools.Log = Tools._LogEnabled;
  2217. Tools.Warn = Tools._WarnEnabled;
  2218. Tools.Error = Tools._ErrorEnabled;
  2219. return Tools;
  2220. })();
  2221. BABYLON.Tools = Tools;
  2222. })(BABYLON || (BABYLON = {}));
  2223. var BABYLON;
  2224. (function (BABYLON) {
  2225. var _DepthCullingState = (function () {
  2226. function _DepthCullingState() {
  2227. this._isDepthTestDirty = false;
  2228. this._isDepthMaskDirty = false;
  2229. this._isDepthFuncDirty = false;
  2230. this._isCullFaceDirty = false;
  2231. this._isCullDirty = false;
  2232. }
  2233. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2234. get: function () {
  2235. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2236. },
  2237. enumerable: true,
  2238. configurable: true
  2239. });
  2240. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2241. get: function () {
  2242. return this._cullFace;
  2243. },
  2244. set: function (value) {
  2245. if (this._cullFace === value) {
  2246. return;
  2247. }
  2248. this._cullFace = value;
  2249. this._isCullFaceDirty = true;
  2250. },
  2251. enumerable: true,
  2252. configurable: true
  2253. });
  2254. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2255. get: function () {
  2256. return this._cull;
  2257. },
  2258. set: function (value) {
  2259. if (this._cull === value) {
  2260. return;
  2261. }
  2262. this._cull = value;
  2263. this._isCullDirty = true;
  2264. },
  2265. enumerable: true,
  2266. configurable: true
  2267. });
  2268. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2269. get: function () {
  2270. return this._depthFunc;
  2271. },
  2272. set: function (value) {
  2273. if (this._depthFunc === value) {
  2274. return;
  2275. }
  2276. this._depthFunc = value;
  2277. this._isDepthFuncDirty = true;
  2278. },
  2279. enumerable: true,
  2280. configurable: true
  2281. });
  2282. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2283. get: function () {
  2284. return this._depthMask;
  2285. },
  2286. set: function (value) {
  2287. if (this._depthMask === value) {
  2288. return;
  2289. }
  2290. this._depthMask = value;
  2291. this._isDepthMaskDirty = true;
  2292. },
  2293. enumerable: true,
  2294. configurable: true
  2295. });
  2296. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2297. get: function () {
  2298. return this._depthTest;
  2299. },
  2300. set: function (value) {
  2301. if (this._depthTest === value) {
  2302. return;
  2303. }
  2304. this._depthTest = value;
  2305. this._isDepthTestDirty = true;
  2306. },
  2307. enumerable: true,
  2308. configurable: true
  2309. });
  2310. _DepthCullingState.prototype.reset = function () {
  2311. this._depthMask = true;
  2312. this._depthTest = true;
  2313. this._depthFunc = null;
  2314. this._cull = null;
  2315. this._cullFace = null;
  2316. this._isDepthTestDirty = true;
  2317. this._isDepthMaskDirty = true;
  2318. this._isDepthFuncDirty = false;
  2319. this._isCullFaceDirty = false;
  2320. this._isCullDirty = false;
  2321. };
  2322. _DepthCullingState.prototype.apply = function (gl) {
  2323. if (!this.isDirty) {
  2324. return;
  2325. }
  2326. if (this._isCullDirty) {
  2327. if (this.cull === true) {
  2328. gl.enable(gl.CULL_FACE);
  2329. } else if (this.cull === false) {
  2330. gl.disable(gl.CULL_FACE);
  2331. }
  2332. this._isCullDirty = false;
  2333. }
  2334. if (this._isCullFaceDirty) {
  2335. gl.cullFace(this.cullFace);
  2336. this._isCullFaceDirty = false;
  2337. }
  2338. if (this._isDepthMaskDirty) {
  2339. gl.depthMask(this.depthMask);
  2340. this._isDepthMaskDirty = false;
  2341. }
  2342. if (this._isDepthTestDirty) {
  2343. if (this.depthTest === true) {
  2344. gl.enable(gl.DEPTH_TEST);
  2345. } else if (this.depthTest === false) {
  2346. gl.disable(gl.DEPTH_TEST);
  2347. }
  2348. this._isDepthTestDirty = false;
  2349. }
  2350. if (this._isDepthFuncDirty) {
  2351. gl.depthFunc(this.depthFunc);
  2352. this._isDepthFuncDirty = false;
  2353. }
  2354. };
  2355. return _DepthCullingState;
  2356. })();
  2357. BABYLON._DepthCullingState = _DepthCullingState;
  2358. var _AlphaState = (function () {
  2359. function _AlphaState() {
  2360. this._isAlphaBlendDirty = false;
  2361. this._isBlendFunctionParametersDirty = false;
  2362. this._alphaBlend = false;
  2363. this._blendFunctionParameters = new Array(4);
  2364. }
  2365. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2366. get: function () {
  2367. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2368. },
  2369. enumerable: true,
  2370. configurable: true
  2371. });
  2372. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2373. get: function () {
  2374. return this._alphaBlend;
  2375. },
  2376. set: function (value) {
  2377. if (this._alphaBlend === value) {
  2378. return;
  2379. }
  2380. this._alphaBlend = value;
  2381. this._isAlphaBlendDirty = true;
  2382. },
  2383. enumerable: true,
  2384. configurable: true
  2385. });
  2386. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2387. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2388. return;
  2389. }
  2390. this._blendFunctionParameters[0] = value0;
  2391. this._blendFunctionParameters[1] = value1;
  2392. this._blendFunctionParameters[2] = value2;
  2393. this._blendFunctionParameters[3] = value3;
  2394. this._isBlendFunctionParametersDirty = true;
  2395. };
  2396. _AlphaState.prototype.reset = function () {
  2397. this._alphaBlend = false;
  2398. this._blendFunctionParameters[0] = null;
  2399. this._blendFunctionParameters[1] = null;
  2400. this._blendFunctionParameters[2] = null;
  2401. this._blendFunctionParameters[3] = null;
  2402. this._isAlphaBlendDirty = true;
  2403. this._isBlendFunctionParametersDirty = false;
  2404. };
  2405. _AlphaState.prototype.apply = function (gl) {
  2406. if (!this.isDirty) {
  2407. return;
  2408. }
  2409. if (this._isAlphaBlendDirty) {
  2410. if (this._alphaBlend === true) {
  2411. gl.enable(gl.BLEND);
  2412. } else if (this._alphaBlend === false) {
  2413. gl.disable(gl.BLEND);
  2414. }
  2415. this._isAlphaBlendDirty = false;
  2416. }
  2417. if (this._isBlendFunctionParametersDirty) {
  2418. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2419. this._isBlendFunctionParametersDirty = false;
  2420. }
  2421. };
  2422. return _AlphaState;
  2423. })();
  2424. BABYLON._AlphaState = _AlphaState;
  2425. var compileShader = function (gl, source, type, defines) {
  2426. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2427. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2428. gl.compileShader(shader);
  2429. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2430. throw new Error(gl.getShaderInfoLog(shader));
  2431. }
  2432. return shader;
  2433. };
  2434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2435. var magFilter = gl.NEAREST;
  2436. var minFilter = gl.NEAREST;
  2437. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2438. magFilter = gl.LINEAR;
  2439. if (generateMipMaps) {
  2440. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2441. } else {
  2442. minFilter = gl.LINEAR;
  2443. }
  2444. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2445. magFilter = gl.LINEAR;
  2446. if (generateMipMaps) {
  2447. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2448. } else {
  2449. minFilter = gl.LINEAR;
  2450. }
  2451. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2452. magFilter = gl.NEAREST;
  2453. if (generateMipMaps) {
  2454. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2455. } else {
  2456. minFilter = gl.NEAREST;
  2457. }
  2458. }
  2459. return {
  2460. min: minFilter,
  2461. mag: magFilter
  2462. };
  2463. };
  2464. var getExponantOfTwo = function (value, max) {
  2465. var count = 1;
  2466. do {
  2467. count *= 2;
  2468. } while(count < value);
  2469. if (count > max)
  2470. count = max;
  2471. return count;
  2472. };
  2473. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2474. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2475. var engine = scene.getEngine();
  2476. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2477. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2478. gl.bindTexture(gl.TEXTURE_2D, texture);
  2479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2480. processFunction(potWidth, potHeight);
  2481. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2484. if (!noMipmap && !isCompressed) {
  2485. gl.generateMipmap(gl.TEXTURE_2D);
  2486. }
  2487. gl.bindTexture(gl.TEXTURE_2D, null);
  2488. engine._activeTexturesCache = [];
  2489. texture._baseWidth = width;
  2490. texture._baseHeight = height;
  2491. texture._width = potWidth;
  2492. texture._height = potHeight;
  2493. texture.isReady = true;
  2494. scene._removePendingData(texture);
  2495. };
  2496. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2497. var img;
  2498. var onload = function () {
  2499. loadedImages.push(img);
  2500. scene._removePendingData(img);
  2501. if (index != extensions.length - 1) {
  2502. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2503. } else {
  2504. onfinish(loadedImages);
  2505. }
  2506. };
  2507. var onerror = function () {
  2508. scene._removePendingData(img);
  2509. };
  2510. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2511. scene._addPendingData(img);
  2512. };
  2513. var EngineCapabilities = (function () {
  2514. function EngineCapabilities() {
  2515. }
  2516. return EngineCapabilities;
  2517. })();
  2518. BABYLON.EngineCapabilities = EngineCapabilities;
  2519. var Engine = (function () {
  2520. function Engine(canvas, antialias, options) {
  2521. var _this = this;
  2522. this.isFullscreen = false;
  2523. this.isPointerLock = false;
  2524. this.forceWireframe = false;
  2525. this.cullBackFaces = true;
  2526. this.renderEvenInBackground = true;
  2527. this.scenes = new Array();
  2528. this._windowIsBackground = false;
  2529. this._runningLoop = false;
  2530. this._loadingDivBackgroundColor = "black";
  2531. this._depthCullingState = new _DepthCullingState();
  2532. this._alphaState = new _AlphaState();
  2533. this._loadedTexturesCache = new Array();
  2534. this._activeTexturesCache = new Array();
  2535. this._compiledEffects = {};
  2536. this._renderingCanvas = canvas;
  2537. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2538. options = options || {};
  2539. options.antialias = antialias;
  2540. try {
  2541. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2542. } catch (e) {
  2543. throw new Error("WebGL not supported");
  2544. }
  2545. if (!this._gl) {
  2546. throw new Error("WebGL not supported");
  2547. }
  2548. this._onBlur = function () {
  2549. _this._windowIsBackground = true;
  2550. };
  2551. this._onFocus = function () {
  2552. _this._windowIsBackground = false;
  2553. };
  2554. window.addEventListener("blur", this._onBlur);
  2555. window.addEventListener("focus", this._onFocus);
  2556. this._workingCanvas = document.createElement("canvas");
  2557. this._workingContext = this._workingCanvas.getContext("2d");
  2558. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2559. this.resize();
  2560. this._caps = new EngineCapabilities();
  2561. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2562. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2563. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2564. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2565. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2566. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2567. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2568. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  2569. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2570. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2571. this.setDepthBuffer(true);
  2572. this.setDepthFunctionToLessOrEqual();
  2573. this.setDepthWrite(true);
  2574. this._onFullscreenChange = function () {
  2575. if (document.fullscreen !== undefined) {
  2576. _this.isFullscreen = document.fullscreen;
  2577. } else if (document.mozFullScreen !== undefined) {
  2578. _this.isFullscreen = document.mozFullScreen;
  2579. } else if (document.webkitIsFullScreen !== undefined) {
  2580. _this.isFullscreen = document.webkitIsFullScreen;
  2581. } else if (document.msIsFullScreen !== undefined) {
  2582. _this.isFullscreen = document.msIsFullScreen;
  2583. }
  2584. if (_this.isFullscreen && _this._pointerLockRequested) {
  2585. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2586. if (canvas.requestPointerLock) {
  2587. canvas.requestPointerLock();
  2588. }
  2589. }
  2590. };
  2591. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2592. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2593. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2594. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2595. this._onPointerLockChange = function () {
  2596. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2597. };
  2598. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2599. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2600. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2601. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2602. }
  2603. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2604. get: function () {
  2605. return Engine._ALPHA_DISABLE;
  2606. },
  2607. enumerable: true,
  2608. configurable: true
  2609. });
  2610. Object.defineProperty(Engine, "ALPHA_ADD", {
  2611. get: function () {
  2612. return Engine._ALPHA_ADD;
  2613. },
  2614. enumerable: true,
  2615. configurable: true
  2616. });
  2617. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2618. get: function () {
  2619. return Engine._ALPHA_COMBINE;
  2620. },
  2621. enumerable: true,
  2622. configurable: true
  2623. });
  2624. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2625. get: function () {
  2626. return Engine._DELAYLOADSTATE_NONE;
  2627. },
  2628. enumerable: true,
  2629. configurable: true
  2630. });
  2631. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2632. get: function () {
  2633. return Engine._DELAYLOADSTATE_LOADED;
  2634. },
  2635. enumerable: true,
  2636. configurable: true
  2637. });
  2638. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2639. get: function () {
  2640. return Engine._DELAYLOADSTATE_LOADING;
  2641. },
  2642. enumerable: true,
  2643. configurable: true
  2644. });
  2645. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2646. get: function () {
  2647. return Engine._DELAYLOADSTATE_NOTLOADED;
  2648. },
  2649. enumerable: true,
  2650. configurable: true
  2651. });
  2652. Object.defineProperty(Engine, "Version", {
  2653. get: function () {
  2654. return "1.14.0";
  2655. },
  2656. enumerable: true,
  2657. configurable: true
  2658. });
  2659. Engine.prototype.getAspectRatio = function (camera) {
  2660. var viewport = camera.viewport;
  2661. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2662. };
  2663. Engine.prototype.getRenderWidth = function () {
  2664. if (this._currentRenderTarget) {
  2665. return this._currentRenderTarget._width;
  2666. }
  2667. return this._renderingCanvas.width;
  2668. };
  2669. Engine.prototype.getRenderHeight = function () {
  2670. if (this._currentRenderTarget) {
  2671. return this._currentRenderTarget._height;
  2672. }
  2673. return this._renderingCanvas.height;
  2674. };
  2675. Engine.prototype.getRenderingCanvas = function () {
  2676. return this._renderingCanvas;
  2677. };
  2678. Engine.prototype.getRenderingCanvasClientRect = function () {
  2679. return this._renderingCanvas.getBoundingClientRect();
  2680. };
  2681. Engine.prototype.setHardwareScalingLevel = function (level) {
  2682. this._hardwareScalingLevel = level;
  2683. this.resize();
  2684. };
  2685. Engine.prototype.getHardwareScalingLevel = function () {
  2686. return this._hardwareScalingLevel;
  2687. };
  2688. Engine.prototype.getLoadedTexturesCache = function () {
  2689. return this._loadedTexturesCache;
  2690. };
  2691. Engine.prototype.getCaps = function () {
  2692. return this._caps;
  2693. };
  2694. Engine.prototype.setDepthFunctionToGreater = function () {
  2695. this._depthCullingState.depthFunc = this._gl.GREATER;
  2696. };
  2697. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2698. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2699. };
  2700. Engine.prototype.setDepthFunctionToLess = function () {
  2701. this._depthCullingState.depthFunc = this._gl.LESS;
  2702. };
  2703. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2704. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2705. };
  2706. Engine.prototype.stopRenderLoop = function () {
  2707. this._renderFunction = null;
  2708. this._runningLoop = false;
  2709. };
  2710. Engine.prototype._renderLoop = function () {
  2711. var _this = this;
  2712. var shouldRender = true;
  2713. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2714. shouldRender = false;
  2715. }
  2716. if (shouldRender) {
  2717. this.beginFrame();
  2718. if (this._renderFunction) {
  2719. this._renderFunction();
  2720. }
  2721. this.endFrame();
  2722. }
  2723. if (this._runningLoop) {
  2724. BABYLON.Tools.QueueNewFrame(function () {
  2725. _this._renderLoop();
  2726. });
  2727. }
  2728. };
  2729. Engine.prototype.runRenderLoop = function (renderFunction) {
  2730. var _this = this;
  2731. this._runningLoop = true;
  2732. this._renderFunction = renderFunction;
  2733. BABYLON.Tools.QueueNewFrame(function () {
  2734. _this._renderLoop();
  2735. });
  2736. };
  2737. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2738. if (this.isFullscreen) {
  2739. BABYLON.Tools.ExitFullscreen();
  2740. } else {
  2741. this._pointerLockRequested = requestPointerLock;
  2742. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2743. }
  2744. };
  2745. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2746. this.applyStates();
  2747. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2748. if (this._depthCullingState.depthMask) {
  2749. this._gl.clearDepth(1.0);
  2750. }
  2751. var mode = 0;
  2752. if (backBuffer)
  2753. mode |= this._gl.COLOR_BUFFER_BIT;
  2754. if (depthStencil && this._depthCullingState.depthMask)
  2755. mode |= this._gl.DEPTH_BUFFER_BIT;
  2756. this._gl.clear(mode);
  2757. };
  2758. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2759. var width = requiredWidth || this._renderingCanvas.width;
  2760. var height = requiredHeight || this._renderingCanvas.height;
  2761. var x = viewport.x || 0;
  2762. var y = viewport.y || 0;
  2763. this._cachedViewport = viewport;
  2764. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2765. };
  2766. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2767. this._cachedViewport = null;
  2768. this._gl.viewport(x, y, width, height);
  2769. };
  2770. Engine.prototype.beginFrame = function () {
  2771. BABYLON.Tools._MeasureFps();
  2772. };
  2773. Engine.prototype.endFrame = function () {
  2774. this.flushFramebuffer();
  2775. };
  2776. Engine.prototype.resize = function () {
  2777. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2778. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2779. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2780. };
  2781. Engine.prototype.bindFramebuffer = function (texture) {
  2782. this._currentRenderTarget = texture;
  2783. var gl = this._gl;
  2784. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2785. this._gl.viewport(0, 0, texture._width, texture._height);
  2786. this.wipeCaches();
  2787. };
  2788. Engine.prototype.unBindFramebuffer = function (texture) {
  2789. this._currentRenderTarget = null;
  2790. if (texture.generateMipMaps) {
  2791. var gl = this._gl;
  2792. gl.bindTexture(gl.TEXTURE_2D, texture);
  2793. gl.generateMipmap(gl.TEXTURE_2D);
  2794. gl.bindTexture(gl.TEXTURE_2D, null);
  2795. }
  2796. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2797. };
  2798. Engine.prototype.flushFramebuffer = function () {
  2799. this._gl.flush();
  2800. };
  2801. Engine.prototype.restoreDefaultFramebuffer = function () {
  2802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2803. this.setViewport(this._cachedViewport);
  2804. this.wipeCaches();
  2805. };
  2806. Engine.prototype._resetVertexBufferBinding = function () {
  2807. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2808. this._cachedVertexBuffers = null;
  2809. };
  2810. Engine.prototype.createVertexBuffer = function (vertices) {
  2811. var vbo = this._gl.createBuffer();
  2812. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2813. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2814. this._resetVertexBufferBinding();
  2815. vbo.references = 1;
  2816. return vbo;
  2817. };
  2818. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2819. var vbo = this._gl.createBuffer();
  2820. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2821. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2822. this._resetVertexBufferBinding();
  2823. vbo.references = 1;
  2824. return vbo;
  2825. };
  2826. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2827. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2828. if (vertices instanceof Float32Array) {
  2829. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2830. } else {
  2831. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2832. }
  2833. this._resetVertexBufferBinding();
  2834. };
  2835. Engine.prototype._resetIndexBufferBinding = function () {
  2836. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2837. this._cachedIndexBuffer = null;
  2838. };
  2839. Engine.prototype.createIndexBuffer = function (indices) {
  2840. var vbo = this._gl.createBuffer();
  2841. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2842. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2843. this._resetIndexBufferBinding();
  2844. vbo.references = 1;
  2845. return vbo;
  2846. };
  2847. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2848. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2849. this._cachedVertexBuffers = vertexBuffer;
  2850. this._cachedEffectForVertexBuffers = effect;
  2851. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2852. var offset = 0;
  2853. for (var index = 0; index < vertexDeclaration.length; index++) {
  2854. var order = effect.getAttributeLocation(index);
  2855. if (order >= 0) {
  2856. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2857. }
  2858. offset += vertexDeclaration[index] * 4;
  2859. }
  2860. }
  2861. if (this._cachedIndexBuffer !== indexBuffer) {
  2862. this._cachedIndexBuffer = indexBuffer;
  2863. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2864. }
  2865. };
  2866. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2867. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2868. this._cachedVertexBuffers = vertexBuffers;
  2869. this._cachedEffectForVertexBuffers = effect;
  2870. var attributes = effect.getAttributesNames();
  2871. for (var index = 0; index < attributes.length; index++) {
  2872. var order = effect.getAttributeLocation(index);
  2873. if (order >= 0) {
  2874. var vertexBuffer = vertexBuffers[attributes[index]];
  2875. if (!vertexBuffer) {
  2876. continue;
  2877. }
  2878. var stride = vertexBuffer.getStrideSize();
  2879. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2880. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2881. }
  2882. }
  2883. }
  2884. if (this._cachedIndexBuffer !== indexBuffer) {
  2885. this._cachedIndexBuffer = indexBuffer;
  2886. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2887. }
  2888. };
  2889. Engine.prototype._releaseBuffer = function (buffer) {
  2890. buffer.references--;
  2891. if (buffer.references === 0) {
  2892. this._gl.deleteBuffer(buffer);
  2893. return true;
  2894. }
  2895. return false;
  2896. };
  2897. Engine.prototype.createInstancesBuffer = function (capacity) {
  2898. var buffer = this._gl.createBuffer();
  2899. buffer.capacity = capacity;
  2900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2901. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2902. return buffer;
  2903. };
  2904. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2905. this._gl.deleteBuffer(buffer);
  2906. };
  2907. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2909. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2910. for (var index = 0; index < 4; index++) {
  2911. var offsetLocation = offsetLocations[index];
  2912. this._gl.enableVertexAttribArray(offsetLocation);
  2913. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2914. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2915. }
  2916. };
  2917. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2919. for (var index = 0; index < 4; index++) {
  2920. var offsetLocation = offsetLocations[index];
  2921. this._gl.disableVertexAttribArray(offsetLocation);
  2922. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2923. }
  2924. };
  2925. Engine.prototype.applyStates = function () {
  2926. this._depthCullingState.apply(this._gl);
  2927. this._alphaState.apply(this._gl);
  2928. };
  2929. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2930. this.applyStates();
  2931. if (instancesCount) {
  2932. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2933. return;
  2934. }
  2935. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2936. };
  2937. Engine.prototype._releaseEffect = function (effect) {
  2938. if (this._compiledEffects[effect._key]) {
  2939. delete this._compiledEffects[effect._key];
  2940. if (effect.getProgram()) {
  2941. this._gl.deleteProgram(effect.getProgram());
  2942. }
  2943. }
  2944. };
  2945. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2946. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2947. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2948. var name = vertex + "+" + fragment + "@" + defines;
  2949. if (this._compiledEffects[name]) {
  2950. return this._compiledEffects[name];
  2951. }
  2952. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2953. effect._key = name;
  2954. this._compiledEffects[name] = effect;
  2955. return effect;
  2956. };
  2957. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2958. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2959. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2960. var shaderProgram = this._gl.createProgram();
  2961. this._gl.attachShader(shaderProgram, vertexShader);
  2962. this._gl.attachShader(shaderProgram, fragmentShader);
  2963. this._gl.linkProgram(shaderProgram);
  2964. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2965. if (!linked) {
  2966. var error = this._gl.getProgramInfoLog(shaderProgram);
  2967. if (error) {
  2968. throw new Error(error);
  2969. }
  2970. }
  2971. this._gl.deleteShader(vertexShader);
  2972. this._gl.deleteShader(fragmentShader);
  2973. return shaderProgram;
  2974. };
  2975. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2976. var results = [];
  2977. for (var index = 0; index < uniformsNames.length; index++) {
  2978. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2979. }
  2980. return results;
  2981. };
  2982. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2983. var results = [];
  2984. for (var index = 0; index < attributesNames.length; index++) {
  2985. try {
  2986. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2987. } catch (e) {
  2988. results.push(-1);
  2989. }
  2990. }
  2991. return results;
  2992. };
  2993. Engine.prototype.enableEffect = function (effect) {
  2994. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  2995. return;
  2996. }
  2997. this._vertexAttribArrays = this._vertexAttribArrays || [];
  2998. this._gl.useProgram(effect.getProgram());
  2999. for (var i in this._vertexAttribArrays) {
  3000. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3001. continue;
  3002. }
  3003. this._vertexAttribArrays[i] = false;
  3004. this._gl.disableVertexAttribArray(i);
  3005. }
  3006. var attributesCount = effect.getAttributesCount();
  3007. for (var index = 0; index < attributesCount; index++) {
  3008. var order = effect.getAttributeLocation(index);
  3009. if (order >= 0) {
  3010. this._vertexAttribArrays[order] = true;
  3011. this._gl.enableVertexAttribArray(order);
  3012. }
  3013. }
  3014. this._currentEffect = effect;
  3015. };
  3016. Engine.prototype.setArray = function (uniform, array) {
  3017. if (!uniform)
  3018. return;
  3019. this._gl.uniform1fv(uniform, array);
  3020. };
  3021. Engine.prototype.setMatrices = function (uniform, matrices) {
  3022. if (!uniform)
  3023. return;
  3024. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3025. };
  3026. Engine.prototype.setMatrix = function (uniform, matrix) {
  3027. if (!uniform)
  3028. return;
  3029. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3030. };
  3031. Engine.prototype.setFloat = function (uniform, value) {
  3032. if (!uniform)
  3033. return;
  3034. this._gl.uniform1f(uniform, value);
  3035. };
  3036. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3037. if (!uniform)
  3038. return;
  3039. this._gl.uniform2f(uniform, x, y);
  3040. };
  3041. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3042. if (!uniform)
  3043. return;
  3044. this._gl.uniform3f(uniform, x, y, z);
  3045. };
  3046. Engine.prototype.setBool = function (uniform, bool) {
  3047. if (!uniform)
  3048. return;
  3049. this._gl.uniform1i(uniform, bool);
  3050. };
  3051. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3052. if (!uniform)
  3053. return;
  3054. this._gl.uniform4f(uniform, x, y, z, w);
  3055. };
  3056. Engine.prototype.setColor3 = function (uniform, color3) {
  3057. if (!uniform)
  3058. return;
  3059. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3060. };
  3061. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3062. if (!uniform)
  3063. return;
  3064. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3065. };
  3066. Engine.prototype.setState = function (culling, force) {
  3067. if (this._depthCullingState.cull !== culling || force) {
  3068. if (culling) {
  3069. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3070. this._depthCullingState.cull = true;
  3071. } else {
  3072. this._depthCullingState.cull = false;
  3073. }
  3074. }
  3075. };
  3076. Engine.prototype.setDepthBuffer = function (enable) {
  3077. this._depthCullingState.depthTest = enable;
  3078. };
  3079. Engine.prototype.getDepthWrite = function () {
  3080. return this._depthCullingState.depthMask;
  3081. };
  3082. Engine.prototype.setDepthWrite = function (enable) {
  3083. this._depthCullingState.depthMask = enable;
  3084. };
  3085. Engine.prototype.setColorWrite = function (enable) {
  3086. this._gl.colorMask(enable, enable, enable, enable);
  3087. };
  3088. Engine.prototype.setAlphaMode = function (mode) {
  3089. switch (mode) {
  3090. case BABYLON.Engine.ALPHA_DISABLE:
  3091. this.setDepthWrite(true);
  3092. this._alphaState.alphaBlend = false;
  3093. break;
  3094. case BABYLON.Engine.ALPHA_COMBINE:
  3095. this.setDepthWrite(false);
  3096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3097. this._alphaState.alphaBlend = true;
  3098. break;
  3099. case BABYLON.Engine.ALPHA_ADD:
  3100. this.setDepthWrite(false);
  3101. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3102. this._alphaState.alphaBlend = true;
  3103. break;
  3104. }
  3105. };
  3106. Engine.prototype.setAlphaTesting = function (enable) {
  3107. this._alphaTest = enable;
  3108. };
  3109. Engine.prototype.getAlphaTesting = function () {
  3110. return this._alphaTest;
  3111. };
  3112. Engine.prototype.wipeCaches = function () {
  3113. this._activeTexturesCache = [];
  3114. this._currentEffect = null;
  3115. this._depthCullingState.reset();
  3116. this._alphaState.reset();
  3117. this._cachedVertexBuffers = null;
  3118. this._cachedIndexBuffer = null;
  3119. this._cachedEffectForVertexBuffers = null;
  3120. };
  3121. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3122. var gl = this._gl;
  3123. gl.bindTexture(gl.TEXTURE_2D, texture);
  3124. var magFilter = gl.NEAREST;
  3125. var minFilter = gl.NEAREST;
  3126. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3127. magFilter = gl.LINEAR;
  3128. minFilter = gl.LINEAR;
  3129. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3130. magFilter = gl.LINEAR;
  3131. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3132. }
  3133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3135. gl.bindTexture(gl.TEXTURE_2D, null);
  3136. };
  3137. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3138. var _this = this;
  3139. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3140. var texture = this._gl.createTexture();
  3141. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3142. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3143. var isTGA = (extension === ".tga");
  3144. scene._addPendingData(texture);
  3145. texture.url = url;
  3146. texture.noMipmap = noMipmap;
  3147. texture.references = 1;
  3148. this._loadedTexturesCache.push(texture);
  3149. if (isTGA) {
  3150. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3151. var data = new Uint8Array(arrayBuffer);
  3152. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3153. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3154. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3155. }, samplingMode);
  3156. }, null, scene.database, true);
  3157. } else if (isDDS) {
  3158. BABYLON.Tools.LoadFile(url, function (data) {
  3159. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3160. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3161. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3162. console.log("loading " + url);
  3163. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3164. }, samplingMode);
  3165. }, null, scene.database, true);
  3166. } else {
  3167. var onload = function (img) {
  3168. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3169. var isPot = (img.width == potWidth && img.height == potHeight);
  3170. if (!isPot) {
  3171. _this._workingCanvas.width = potWidth;
  3172. _this._workingCanvas.height = potHeight;
  3173. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3174. }
  3175. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3176. }, samplingMode);
  3177. };
  3178. var onerror = function () {
  3179. scene._removePendingData(texture);
  3180. };
  3181. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3182. }
  3183. return texture;
  3184. };
  3185. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3186. var texture = this._gl.createTexture();
  3187. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3188. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3189. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3190. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3191. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3193. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3194. this._activeTexturesCache = [];
  3195. texture._baseWidth = width;
  3196. texture._baseHeight = height;
  3197. texture._width = width;
  3198. texture._height = height;
  3199. texture.isReady = false;
  3200. texture.generateMipMaps = generateMipMaps;
  3201. texture.references = 1;
  3202. this._loadedTexturesCache.push(texture);
  3203. return texture;
  3204. };
  3205. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3206. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3207. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3208. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3209. if (texture.generateMipMaps) {
  3210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3211. }
  3212. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3213. this._activeTexturesCache = [];
  3214. texture.isReady = true;
  3215. };
  3216. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3217. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3219. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3220. if (!texture._workingCanvas) {
  3221. texture._workingCanvas = document.createElement("canvas");
  3222. texture._workingContext = texture._workingCanvas.getContext("2d");
  3223. texture._workingCanvas.width = texture._width;
  3224. texture._workingCanvas.height = texture._height;
  3225. }
  3226. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3227. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3228. } else {
  3229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3230. }
  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.createRenderTargetTexture = function (size, options) {
  3239. var generateMipMaps = false;
  3240. var generateDepthBuffer = true;
  3241. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3242. if (options !== undefined) {
  3243. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3244. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3245. if (options.samplingMode !== undefined) {
  3246. samplingMode = options.samplingMode;
  3247. }
  3248. }
  3249. var gl = this._gl;
  3250. var texture = gl.createTexture();
  3251. gl.bindTexture(gl.TEXTURE_2D, texture);
  3252. var width = size.width || size;
  3253. var height = size.height || size;
  3254. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3259. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3260. var depthBuffer;
  3261. if (generateDepthBuffer) {
  3262. depthBuffer = gl.createRenderbuffer();
  3263. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3264. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3265. }
  3266. var framebuffer = gl.createFramebuffer();
  3267. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3268. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3269. if (generateDepthBuffer) {
  3270. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3271. }
  3272. gl.bindTexture(gl.TEXTURE_2D, null);
  3273. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3274. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3275. texture._framebuffer = framebuffer;
  3276. if (generateDepthBuffer) {
  3277. texture._depthBuffer = depthBuffer;
  3278. }
  3279. texture._width = width;
  3280. texture._height = height;
  3281. texture.isReady = true;
  3282. texture.generateMipMaps = generateMipMaps;
  3283. texture.references = 1;
  3284. this._activeTexturesCache = [];
  3285. this._loadedTexturesCache.push(texture);
  3286. return texture;
  3287. };
  3288. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3289. var _this = this;
  3290. var gl = this._gl;
  3291. var texture = gl.createTexture();
  3292. texture.isCube = true;
  3293. texture.url = rootUrl;
  3294. texture.references = 1;
  3295. this._loadedTexturesCache.push(texture);
  3296. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3297. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3298. if (isDDS) {
  3299. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3300. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3301. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3302. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3303. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3304. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3305. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3306. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3307. }
  3308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3309. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3310. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3312. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3313. _this._activeTexturesCache = [];
  3314. texture._width = info.width;
  3315. texture._height = info.height;
  3316. texture.isReady = true;
  3317. }, null, null, true);
  3318. } else {
  3319. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3320. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3321. var height = width;
  3322. _this._workingCanvas.width = width;
  3323. _this._workingCanvas.height = height;
  3324. var faces = [
  3325. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3326. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3327. ];
  3328. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3329. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3330. for (var index = 0; index < faces.length; index++) {
  3331. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3332. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3333. }
  3334. if (!noMipmap) {
  3335. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3336. }
  3337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3339. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3340. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3341. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3342. _this._activeTexturesCache = [];
  3343. texture._width = width;
  3344. texture._height = height;
  3345. texture.isReady = true;
  3346. }, extensions);
  3347. }
  3348. return texture;
  3349. };
  3350. Engine.prototype._releaseTexture = function (texture) {
  3351. var gl = this._gl;
  3352. if (texture._framebuffer) {
  3353. gl.deleteFramebuffer(texture._framebuffer);
  3354. }
  3355. if (texture._depthBuffer) {
  3356. gl.deleteRenderbuffer(texture._depthBuffer);
  3357. }
  3358. gl.deleteTexture(texture);
  3359. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3360. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3361. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3362. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3363. this._activeTexturesCache[channel] = null;
  3364. }
  3365. var index = this._loadedTexturesCache.indexOf(texture);
  3366. if (index !== -1) {
  3367. this._loadedTexturesCache.splice(index, 1);
  3368. }
  3369. };
  3370. Engine.prototype.bindSamplers = function (effect) {
  3371. this._gl.useProgram(effect.getProgram());
  3372. var samplers = effect.getSamplers();
  3373. for (var index = 0; index < samplers.length; index++) {
  3374. var uniform = effect.getUniform(samplers[index]);
  3375. this._gl.uniform1i(uniform, index);
  3376. }
  3377. this._currentEffect = null;
  3378. };
  3379. Engine.prototype._bindTexture = function (channel, texture) {
  3380. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3381. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3382. this._activeTexturesCache[channel] = null;
  3383. };
  3384. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3385. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3386. };
  3387. Engine.prototype.setTexture = function (channel, texture) {
  3388. if (channel < 0) {
  3389. return;
  3390. }
  3391. if (!texture || !texture.isReady()) {
  3392. if (this._activeTexturesCache[channel] != null) {
  3393. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3394. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3395. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3396. this._activeTexturesCache[channel] = null;
  3397. }
  3398. return;
  3399. }
  3400. if (texture instanceof BABYLON.VideoTexture) {
  3401. if (texture.update()) {
  3402. this._activeTexturesCache[channel] = null;
  3403. }
  3404. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3405. texture.delayLoad();
  3406. return;
  3407. }
  3408. if (this._activeTexturesCache[channel] == texture) {
  3409. return;
  3410. }
  3411. this._activeTexturesCache[channel] = texture;
  3412. var internalTexture = texture.getInternalTexture();
  3413. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3414. if (internalTexture.isCube) {
  3415. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3416. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3417. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3418. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3419. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3420. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3421. }
  3422. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3423. } else {
  3424. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3425. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3426. internalTexture._cachedWrapU = texture.wrapU;
  3427. switch (texture.wrapU) {
  3428. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3429. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3430. break;
  3431. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3432. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3433. break;
  3434. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3435. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3436. break;
  3437. }
  3438. }
  3439. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3440. internalTexture._cachedWrapV = texture.wrapV;
  3441. switch (texture.wrapV) {
  3442. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3443. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3444. break;
  3445. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3446. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3447. break;
  3448. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3449. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3450. break;
  3451. }
  3452. }
  3453. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3454. }
  3455. };
  3456. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3457. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3458. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3459. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3460. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3461. }
  3462. };
  3463. Engine.prototype.readPixels = function (x, y, width, height) {
  3464. var data = new Uint8Array(height * width * 4);
  3465. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3466. return data;
  3467. };
  3468. Engine.prototype.dispose = function () {
  3469. this.hideLoadingUI();
  3470. this.stopRenderLoop();
  3471. while (this.scenes.length) {
  3472. this.scenes[0].dispose();
  3473. }
  3474. for (var name in this._compiledEffects) {
  3475. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3476. }
  3477. for (var i in this._vertexAttribArrays) {
  3478. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3479. continue;
  3480. }
  3481. this._gl.disableVertexAttribArray(i);
  3482. }
  3483. window.removeEventListener("blur", this._onBlur);
  3484. window.removeEventListener("focus", this._onFocus);
  3485. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3486. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3487. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3488. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3489. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3490. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3491. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3492. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3493. };
  3494. Engine.prototype.displayLoadingUI = function () {
  3495. var _this = this;
  3496. this._loadingDiv = document.createElement("div");
  3497. this._loadingDiv.style.opacity = "0";
  3498. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3499. this._loadingTextDiv = document.createElement("div");
  3500. this._loadingTextDiv.style.position = "absolute";
  3501. this._loadingTextDiv.style.left = "0";
  3502. this._loadingTextDiv.style.top = "50%";
  3503. this._loadingTextDiv.style.marginTop = "80px";
  3504. this._loadingTextDiv.style.width = "100%";
  3505. this._loadingTextDiv.style.height = "20px";
  3506. this._loadingTextDiv.style.fontFamily = "Arial";
  3507. this._loadingTextDiv.style.fontSize = "14px";
  3508. this._loadingTextDiv.style.color = "white";
  3509. this._loadingTextDiv.style.textAlign = "center";
  3510. this._loadingTextDiv.innerHTML = "Loading";
  3511. this._loadingDiv.appendChild(this._loadingTextDiv);
  3512. var imgBack = new Image();
  3513. 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==";
  3514. imgBack.style.position = "absolute";
  3515. imgBack.style.left = "50%";
  3516. imgBack.style.top = "50%";
  3517. imgBack.style.marginLeft = "-50px";
  3518. imgBack.style.marginTop = "-50px";
  3519. imgBack.style.transition = "transform 1.0s ease";
  3520. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3521. var deg = 360;
  3522. var onTransitionEnd = function () {
  3523. deg += 360;
  3524. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3525. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3526. };
  3527. imgBack.addEventListener("transitionend", onTransitionEnd);
  3528. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3529. this._loadingDiv.appendChild(imgBack);
  3530. var imgFront = new Image();
  3531. 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=";
  3532. imgFront.style.position = "absolute";
  3533. imgFront.style.left = "50%";
  3534. imgFront.style.top = "50%";
  3535. imgFront.style.marginLeft = "-50px";
  3536. imgFront.style.marginTop = "-50px";
  3537. this._loadingDiv.appendChild(imgFront);
  3538. this._resizeLoadingUI = function () {
  3539. var canvasRect = _this.getRenderingCanvasClientRect();
  3540. _this._loadingDiv.style.position = "absolute";
  3541. _this._loadingDiv.style.left = canvasRect.left + "px";
  3542. _this._loadingDiv.style.top = canvasRect.top + "px";
  3543. _this._loadingDiv.style.width = canvasRect.width + "px";
  3544. _this._loadingDiv.style.height = canvasRect.height + "px";
  3545. };
  3546. this._resizeLoadingUI();
  3547. window.addEventListener("resize", this._resizeLoadingUI);
  3548. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3549. document.body.appendChild(this._loadingDiv);
  3550. setTimeout(function () {
  3551. _this._loadingDiv.style.opacity = "1";
  3552. imgBack.style.transform = "rotateZ(360deg)";
  3553. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3554. }, 0);
  3555. };
  3556. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3557. set: function (text) {
  3558. if (!this._loadingDiv) {
  3559. return;
  3560. }
  3561. this._loadingTextDiv.innerHTML = text;
  3562. },
  3563. enumerable: true,
  3564. configurable: true
  3565. });
  3566. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3567. get: function () {
  3568. return this._loadingDivBackgroundColor;
  3569. },
  3570. set: function (color) {
  3571. this._loadingDivBackgroundColor = color;
  3572. if (!this._loadingDiv) {
  3573. return;
  3574. }
  3575. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3576. },
  3577. enumerable: true,
  3578. configurable: true
  3579. });
  3580. Engine.prototype.hideLoadingUI = function () {
  3581. var _this = this;
  3582. if (!this._loadingDiv) {
  3583. return;
  3584. }
  3585. var onTransitionEnd = function () {
  3586. if (!_this._loadingDiv) {
  3587. return;
  3588. }
  3589. document.body.removeChild(_this._loadingDiv);
  3590. window.removeEventListener("resize", _this._resizeLoadingUI);
  3591. _this._loadingDiv = null;
  3592. };
  3593. this._loadingDiv.style.opacity = "0";
  3594. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3595. };
  3596. Engine.isSupported = function () {
  3597. try {
  3598. var tempcanvas = document.createElement("canvas");
  3599. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3600. return gl != null && !!window.WebGLRenderingContext;
  3601. } catch (e) {
  3602. return false;
  3603. }
  3604. };
  3605. Engine._ALPHA_DISABLE = 0;
  3606. Engine._ALPHA_ADD = 1;
  3607. Engine._ALPHA_COMBINE = 2;
  3608. Engine._DELAYLOADSTATE_NONE = 0;
  3609. Engine._DELAYLOADSTATE_LOADED = 1;
  3610. Engine._DELAYLOADSTATE_LOADING = 2;
  3611. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3612. Engine.Epsilon = 0.001;
  3613. Engine.CollisionsEpsilon = 0.001;
  3614. Engine.ShadersRepository = "Babylon/Shaders/";
  3615. return Engine;
  3616. })();
  3617. BABYLON.Engine = Engine;
  3618. })(BABYLON || (BABYLON = {}));
  3619. var BABYLON;
  3620. (function (BABYLON) {
  3621. var Node = (function () {
  3622. function Node(name, scene) {
  3623. this.state = "";
  3624. this.animations = new Array();
  3625. this._childrenFlag = -1;
  3626. this._isEnabled = true;
  3627. this._isReady = true;
  3628. this._currentRenderId = -1;
  3629. this.name = name;
  3630. this.id = name;
  3631. this._scene = scene;
  3632. this._initCache();
  3633. }
  3634. Node.prototype.getScene = function () {
  3635. return this._scene;
  3636. };
  3637. Node.prototype.getEngine = function () {
  3638. return this._scene.getEngine();
  3639. };
  3640. Node.prototype.getWorldMatrix = function () {
  3641. return BABYLON.Matrix.Identity();
  3642. };
  3643. Node.prototype._initCache = function () {
  3644. this._cache = {};
  3645. this._cache.parent = undefined;
  3646. };
  3647. Node.prototype.updateCache = function (force) {
  3648. if (!force && this.isSynchronized())
  3649. return;
  3650. this._cache.parent = this.parent;
  3651. this._updateCache();
  3652. };
  3653. Node.prototype._updateCache = function (ignoreParentClass) {
  3654. };
  3655. Node.prototype._isSynchronized = function () {
  3656. return true;
  3657. };
  3658. Node.prototype.isSynchronizedWithParent = function () {
  3659. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3660. };
  3661. Node.prototype.isSynchronized = function (updateCache) {
  3662. var check = this.hasNewParent();
  3663. check = check || !this.isSynchronizedWithParent();
  3664. check = check || !this._isSynchronized();
  3665. if (updateCache)
  3666. this.updateCache(true);
  3667. return !check;
  3668. };
  3669. Node.prototype.hasNewParent = function (update) {
  3670. if (this._cache.parent === this.parent)
  3671. return false;
  3672. if (update)
  3673. this._cache.parent = this.parent;
  3674. return true;
  3675. };
  3676. Node.prototype.isReady = function () {
  3677. return this._isReady;
  3678. };
  3679. Node.prototype.isEnabled = function () {
  3680. if (!this._isEnabled) {
  3681. return false;
  3682. }
  3683. if (this.parent) {
  3684. return this.parent.isEnabled();
  3685. }
  3686. return true;
  3687. };
  3688. Node.prototype.setEnabled = function (value) {
  3689. this._isEnabled = value;
  3690. };
  3691. Node.prototype.isDescendantOf = function (ancestor) {
  3692. if (this.parent) {
  3693. if (this.parent === ancestor) {
  3694. return true;
  3695. }
  3696. return this.parent.isDescendantOf(ancestor);
  3697. }
  3698. return false;
  3699. };
  3700. Node.prototype._getDescendants = function (list, results) {
  3701. for (var index = 0; index < list.length; index++) {
  3702. var item = list[index];
  3703. if (item.isDescendantOf(this)) {
  3704. results.push(item);
  3705. }
  3706. }
  3707. };
  3708. Node.prototype.getDescendants = function () {
  3709. var results = [];
  3710. this._getDescendants(this._scene.meshes, results);
  3711. this._getDescendants(this._scene.lights, results);
  3712. this._getDescendants(this._scene.cameras, results);
  3713. return results;
  3714. };
  3715. Node.prototype._setReady = function (state) {
  3716. if (state == this._isReady) {
  3717. return;
  3718. }
  3719. if (!state) {
  3720. this._isReady = false;
  3721. return;
  3722. }
  3723. this._isReady = true;
  3724. if (this.onReady) {
  3725. this.onReady(this);
  3726. }
  3727. };
  3728. return Node;
  3729. })();
  3730. BABYLON.Node = Node;
  3731. })(BABYLON || (BABYLON = {}));
  3732. var BABYLON;
  3733. (function (BABYLON) {
  3734. var BoundingSphere = (function () {
  3735. function BoundingSphere(minimum, maximum) {
  3736. this.minimum = minimum;
  3737. this.maximum = maximum;
  3738. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3739. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3740. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3741. this.radius = distance * 0.5;
  3742. this.centerWorld = BABYLON.Vector3.Zero();
  3743. this._update(BABYLON.Matrix.Identity());
  3744. }
  3745. BoundingSphere.prototype._update = function (world) {
  3746. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3747. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3748. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3749. };
  3750. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3751. for (var i = 0; i < 6; i++) {
  3752. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3753. return false;
  3754. }
  3755. return true;
  3756. };
  3757. BoundingSphere.prototype.intersectsPoint = function (point) {
  3758. var x = this.centerWorld.x - point.x;
  3759. var y = this.centerWorld.y - point.y;
  3760. var z = this.centerWorld.z - point.z;
  3761. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3762. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3763. return false;
  3764. return true;
  3765. };
  3766. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3767. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3768. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3769. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3770. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3771. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3772. return false;
  3773. return true;
  3774. };
  3775. return BoundingSphere;
  3776. })();
  3777. BABYLON.BoundingSphere = BoundingSphere;
  3778. })(BABYLON || (BABYLON = {}));
  3779. var BABYLON;
  3780. (function (BABYLON) {
  3781. var BoundingBox = (function () {
  3782. function BoundingBox(minimum, maximum) {
  3783. this.minimum = minimum;
  3784. this.maximum = maximum;
  3785. this.vectors = new Array();
  3786. this.vectorsWorld = new Array();
  3787. this.vectors.push(this.minimum.clone());
  3788. this.vectors.push(this.maximum.clone());
  3789. this.vectors.push(this.minimum.clone());
  3790. this.vectors[2].x = this.maximum.x;
  3791. this.vectors.push(this.minimum.clone());
  3792. this.vectors[3].y = this.maximum.y;
  3793. this.vectors.push(this.minimum.clone());
  3794. this.vectors[4].z = this.maximum.z;
  3795. this.vectors.push(this.maximum.clone());
  3796. this.vectors[5].z = this.minimum.z;
  3797. this.vectors.push(this.maximum.clone());
  3798. this.vectors[6].x = this.minimum.x;
  3799. this.vectors.push(this.maximum.clone());
  3800. this.vectors[7].y = this.minimum.y;
  3801. this.center = this.maximum.add(this.minimum).scale(0.5);
  3802. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3803. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3804. for (var index = 0; index < this.vectors.length; index++) {
  3805. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3806. }
  3807. this.minimumWorld = BABYLON.Vector3.Zero();
  3808. this.maximumWorld = BABYLON.Vector3.Zero();
  3809. this._update(BABYLON.Matrix.Identity());
  3810. }
  3811. BoundingBox.prototype.getWorldMatrix = function () {
  3812. return this._worldMatrix;
  3813. };
  3814. BoundingBox.prototype._update = function (world) {
  3815. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3816. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3817. for (var index = 0; index < this.vectors.length; index++) {
  3818. var v = this.vectorsWorld[index];
  3819. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3820. if (v.x < this.minimumWorld.x)
  3821. this.minimumWorld.x = v.x;
  3822. if (v.y < this.minimumWorld.y)
  3823. this.minimumWorld.y = v.y;
  3824. if (v.z < this.minimumWorld.z)
  3825. this.minimumWorld.z = v.z;
  3826. if (v.x > this.maximumWorld.x)
  3827. this.maximumWorld.x = v.x;
  3828. if (v.y > this.maximumWorld.y)
  3829. this.maximumWorld.y = v.y;
  3830. if (v.z > this.maximumWorld.z)
  3831. this.maximumWorld.z = v.z;
  3832. }
  3833. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3834. this.center.scaleInPlace(0.5);
  3835. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3836. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3837. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3838. this._worldMatrix = world;
  3839. };
  3840. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3841. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3842. };
  3843. BoundingBox.prototype.intersectsPoint = function (point) {
  3844. var delta = BABYLON.Engine.Epsilon;
  3845. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3846. return false;
  3847. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3848. return false;
  3849. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3850. return false;
  3851. return true;
  3852. };
  3853. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3854. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3855. };
  3856. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3857. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3858. return false;
  3859. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3860. return false;
  3861. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3862. return false;
  3863. return true;
  3864. };
  3865. BoundingBox.Intersects = function (box0, box1) {
  3866. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3867. return false;
  3868. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3869. return false;
  3870. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3871. return false;
  3872. return true;
  3873. };
  3874. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3875. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3876. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3877. return (num <= (sphereRadius * sphereRadius));
  3878. };
  3879. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3880. for (var p = 0; p < 6; p++) {
  3881. var inCount = 8;
  3882. for (var i = 0; i < 8; i++) {
  3883. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3884. --inCount;
  3885. } else {
  3886. break;
  3887. }
  3888. }
  3889. if (inCount == 0)
  3890. return false;
  3891. }
  3892. return true;
  3893. };
  3894. return BoundingBox;
  3895. })();
  3896. BABYLON.BoundingBox = BoundingBox;
  3897. })(BABYLON || (BABYLON = {}));
  3898. var BABYLON;
  3899. (function (BABYLON) {
  3900. var computeBoxExtents = function (axis, box) {
  3901. var p = BABYLON.Vector3.Dot(box.center, axis);
  3902. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3903. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3904. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3905. var r = r0 + r1 + r2;
  3906. return {
  3907. min: p - r,
  3908. max: p + r
  3909. };
  3910. };
  3911. var extentsOverlap = function (min0, max0, min1, max1) {
  3912. return !(min0 > max1 || min1 > max0);
  3913. };
  3914. var axisOverlap = function (axis, box0, box1) {
  3915. var result0 = computeBoxExtents(axis, box0);
  3916. var result1 = computeBoxExtents(axis, box1);
  3917. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3918. };
  3919. var BoundingInfo = (function () {
  3920. function BoundingInfo(minimum, maximum) {
  3921. this.minimum = minimum;
  3922. this.maximum = maximum;
  3923. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3924. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3925. }
  3926. BoundingInfo.prototype._update = function (world) {
  3927. this.boundingBox._update(world);
  3928. this.boundingSphere._update(world);
  3929. };
  3930. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3931. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3932. return false;
  3933. return this.boundingBox.isInFrustum(frustumPlanes);
  3934. };
  3935. BoundingInfo.prototype._checkCollision = function (collider) {
  3936. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3937. };
  3938. BoundingInfo.prototype.intersectsPoint = function (point) {
  3939. if (!this.boundingSphere.centerWorld) {
  3940. return false;
  3941. }
  3942. if (!this.boundingSphere.intersectsPoint(point)) {
  3943. return false;
  3944. }
  3945. if (!this.boundingBox.intersectsPoint(point)) {
  3946. return false;
  3947. }
  3948. return true;
  3949. };
  3950. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3951. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3952. return false;
  3953. }
  3954. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3955. return false;
  3956. }
  3957. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3958. return false;
  3959. }
  3960. if (!precise) {
  3961. return true;
  3962. }
  3963. var box0 = this.boundingBox;
  3964. var box1 = boundingInfo.boundingBox;
  3965. if (!axisOverlap(box0.directions[0], box0, box1))
  3966. return false;
  3967. if (!axisOverlap(box0.directions[1], box0, box1))
  3968. return false;
  3969. if (!axisOverlap(box0.directions[2], box0, box1))
  3970. return false;
  3971. if (!axisOverlap(box1.directions[0], box0, box1))
  3972. return false;
  3973. if (!axisOverlap(box1.directions[1], box0, box1))
  3974. return false;
  3975. if (!axisOverlap(box1.directions[2], box0, box1))
  3976. return false;
  3977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3978. return false;
  3979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3980. return false;
  3981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3982. return false;
  3983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3984. return false;
  3985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3986. return false;
  3987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3988. return false;
  3989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3990. return false;
  3991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  3992. return false;
  3993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  3994. return false;
  3995. return true;
  3996. };
  3997. return BoundingInfo;
  3998. })();
  3999. BABYLON.BoundingInfo = BoundingInfo;
  4000. })(BABYLON || (BABYLON = {}));
  4001. var __extends = this.__extends || function (d, b) {
  4002. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4003. function __() { this.constructor = d; }
  4004. __.prototype = b.prototype;
  4005. d.prototype = new __();
  4006. };
  4007. var BABYLON;
  4008. (function (BABYLON) {
  4009. var Light = (function (_super) {
  4010. __extends(Light, _super);
  4011. function Light(name, scene) {
  4012. _super.call(this, name, scene);
  4013. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4014. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4015. this.intensity = 1.0;
  4016. this.range = Number.MAX_VALUE;
  4017. this.includedOnlyMeshes = new Array();
  4018. this.excludedMeshes = new Array();
  4019. this._excludedMeshesIds = new Array();
  4020. this._includedOnlyMeshesIds = new Array();
  4021. scene.lights.push(this);
  4022. }
  4023. Light.prototype.getShadowGenerator = function () {
  4024. return this._shadowGenerator;
  4025. };
  4026. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4027. };
  4028. Light.prototype._getWorldMatrix = function () {
  4029. return BABYLON.Matrix.Identity();
  4030. };
  4031. Light.prototype.canAffectMesh = function (mesh) {
  4032. if (!mesh) {
  4033. return true;
  4034. }
  4035. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4036. return false;
  4037. }
  4038. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4039. return false;
  4040. }
  4041. return true;
  4042. };
  4043. Light.prototype.getWorldMatrix = function () {
  4044. this._currentRenderId = this.getScene().getRenderId();
  4045. var worldMatrix = this._getWorldMatrix();
  4046. if (this.parent && this.parent.getWorldMatrix) {
  4047. if (!this._parentedWorldMatrix) {
  4048. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4049. }
  4050. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4051. return this._parentedWorldMatrix;
  4052. }
  4053. return worldMatrix;
  4054. };
  4055. Light.prototype.dispose = function () {
  4056. if (this._shadowGenerator) {
  4057. this._shadowGenerator.dispose();
  4058. this._shadowGenerator = null;
  4059. }
  4060. var index = this.getScene().lights.indexOf(this);
  4061. this.getScene().lights.splice(index, 1);
  4062. };
  4063. return Light;
  4064. })(BABYLON.Node);
  4065. BABYLON.Light = Light;
  4066. })(BABYLON || (BABYLON = {}));
  4067. var __extends = this.__extends || function (d, b) {
  4068. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4069. function __() { this.constructor = d; }
  4070. __.prototype = b.prototype;
  4071. d.prototype = new __();
  4072. };
  4073. var BABYLON;
  4074. (function (BABYLON) {
  4075. var PointLight = (function (_super) {
  4076. __extends(PointLight, _super);
  4077. function PointLight(name, position, scene) {
  4078. _super.call(this, name, scene);
  4079. this.position = position;
  4080. }
  4081. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4082. if (this.parent && this.parent.getWorldMatrix) {
  4083. if (!this._transformedPosition) {
  4084. this._transformedPosition = BABYLON.Vector3.Zero();
  4085. }
  4086. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4087. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4088. return;
  4089. }
  4090. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4091. };
  4092. PointLight.prototype.getShadowGenerator = function () {
  4093. return null;
  4094. };
  4095. PointLight.prototype._getWorldMatrix = function () {
  4096. if (!this._worldMatrix) {
  4097. this._worldMatrix = BABYLON.Matrix.Identity();
  4098. }
  4099. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4100. return this._worldMatrix;
  4101. };
  4102. return PointLight;
  4103. })(BABYLON.Light);
  4104. BABYLON.PointLight = PointLight;
  4105. })(BABYLON || (BABYLON = {}));
  4106. var __extends = this.__extends || function (d, b) {
  4107. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4108. function __() { this.constructor = d; }
  4109. __.prototype = b.prototype;
  4110. d.prototype = new __();
  4111. };
  4112. var BABYLON;
  4113. (function (BABYLON) {
  4114. var SpotLight = (function (_super) {
  4115. __extends(SpotLight, _super);
  4116. function SpotLight(name, position, direction, angle, exponent, scene) {
  4117. _super.call(this, name, scene);
  4118. this.position = position;
  4119. this.direction = direction;
  4120. this.angle = angle;
  4121. this.exponent = exponent;
  4122. }
  4123. SpotLight.prototype.setDirectionToTarget = function (target) {
  4124. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4125. return this.direction;
  4126. };
  4127. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4128. var normalizeDirection;
  4129. if (this.parent && this.parent.getWorldMatrix) {
  4130. if (!this._transformedDirection) {
  4131. this._transformedDirection = BABYLON.Vector3.Zero();
  4132. }
  4133. if (!this._transformedPosition) {
  4134. this._transformedPosition = BABYLON.Vector3.Zero();
  4135. }
  4136. var parentWorldMatrix = this.parent.getWorldMatrix();
  4137. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4138. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4139. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4140. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4141. } else {
  4142. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4143. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4144. }
  4145. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4146. };
  4147. SpotLight.prototype._getWorldMatrix = function () {
  4148. if (!this._worldMatrix) {
  4149. this._worldMatrix = BABYLON.Matrix.Identity();
  4150. }
  4151. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4152. return this._worldMatrix;
  4153. };
  4154. return SpotLight;
  4155. })(BABYLON.Light);
  4156. BABYLON.SpotLight = SpotLight;
  4157. })(BABYLON || (BABYLON = {}));
  4158. var __extends = this.__extends || function (d, b) {
  4159. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4160. function __() { this.constructor = d; }
  4161. __.prototype = b.prototype;
  4162. d.prototype = new __();
  4163. };
  4164. var BABYLON;
  4165. (function (BABYLON) {
  4166. var DirectionalLight = (function (_super) {
  4167. __extends(DirectionalLight, _super);
  4168. function DirectionalLight(name, direction, scene) {
  4169. _super.call(this, name, scene);
  4170. this.direction = direction;
  4171. this.position = direction.scale(-1);
  4172. }
  4173. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4174. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4175. return this.direction;
  4176. };
  4177. DirectionalLight.prototype._computeTransformedPosition = function () {
  4178. if (this.parent && this.parent.getWorldMatrix) {
  4179. if (!this._transformedPosition) {
  4180. this._transformedPosition = BABYLON.Vector3.Zero();
  4181. }
  4182. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4183. return true;
  4184. }
  4185. return false;
  4186. };
  4187. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4188. if (this.parent && this.parent.getWorldMatrix) {
  4189. if (!this._transformedDirection) {
  4190. this._transformedDirection = BABYLON.Vector3.Zero();
  4191. }
  4192. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4193. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4194. return;
  4195. }
  4196. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4197. };
  4198. DirectionalLight.prototype._getWorldMatrix = function () {
  4199. if (!this._worldMatrix) {
  4200. this._worldMatrix = BABYLON.Matrix.Identity();
  4201. }
  4202. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4203. return this._worldMatrix;
  4204. };
  4205. return DirectionalLight;
  4206. })(BABYLON.Light);
  4207. BABYLON.DirectionalLight = DirectionalLight;
  4208. })(BABYLON || (BABYLON = {}));
  4209. var BABYLON;
  4210. (function (BABYLON) {
  4211. var ShadowGenerator = (function () {
  4212. function ShadowGenerator(mapSize, light) {
  4213. var _this = this;
  4214. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4215. this._darkness = 0;
  4216. this._transparencyShadow = false;
  4217. this._viewMatrix = BABYLON.Matrix.Zero();
  4218. this._projectionMatrix = BABYLON.Matrix.Zero();
  4219. this._transformMatrix = BABYLON.Matrix.Zero();
  4220. this._worldViewProjection = BABYLON.Matrix.Zero();
  4221. this._light = light;
  4222. this._scene = light.getScene();
  4223. light._shadowGenerator = this;
  4224. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4225. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4226. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4227. this._shadowMap.renderParticles = false;
  4228. var renderSubMesh = function (subMesh) {
  4229. var mesh = subMesh.getRenderingMesh();
  4230. var scene = _this._scene;
  4231. var engine = scene.getEngine();
  4232. engine.setState(subMesh.getMaterial().backFaceCulling);
  4233. var batch = mesh._getInstancesRenderList(subMesh._id);
  4234. if (batch.mustReturn) {
  4235. return;
  4236. }
  4237. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4238. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4239. engine.enableEffect(_this._effect);
  4240. mesh._bind(subMesh, _this._effect, false);
  4241. var material = subMesh.getMaterial();
  4242. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4243. if (material && material.needAlphaTesting()) {
  4244. var alphaTexture = material.getAlphaTestTexture();
  4245. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4246. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4247. }
  4248. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4249. if (useBones) {
  4250. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4251. }
  4252. if (hardwareInstancedRendering) {
  4253. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4254. } else {
  4255. if (batch.renderSelf[subMesh._id]) {
  4256. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4257. mesh._draw(subMesh, true);
  4258. }
  4259. if (batch.visibleInstances[subMesh._id]) {
  4260. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4261. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4262. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4263. mesh._draw(subMesh, true);
  4264. }
  4265. }
  4266. }
  4267. } else {
  4268. _this._shadowMap.resetRefreshCounter();
  4269. }
  4270. };
  4271. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4272. var index;
  4273. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4274. renderSubMesh(opaqueSubMeshes.data[index]);
  4275. }
  4276. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4277. renderSubMesh(alphaTestSubMeshes.data[index]);
  4278. }
  4279. if (_this._transparencyShadow) {
  4280. for (index = 0; index < transparentSubMeshes.length; index++) {
  4281. renderSubMesh(transparentSubMeshes.data[index]);
  4282. }
  4283. }
  4284. };
  4285. }
  4286. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4287. get: function () {
  4288. return ShadowGenerator._FILTER_NONE;
  4289. },
  4290. enumerable: true,
  4291. configurable: true
  4292. });
  4293. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4294. get: function () {
  4295. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4296. },
  4297. enumerable: true,
  4298. configurable: true
  4299. });
  4300. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4301. get: function () {
  4302. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4303. },
  4304. enumerable: true,
  4305. configurable: true
  4306. });
  4307. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4308. get: function () {
  4309. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4310. },
  4311. set: function (value) {
  4312. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4313. },
  4314. enumerable: true,
  4315. configurable: true
  4316. });
  4317. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4318. get: function () {
  4319. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4320. },
  4321. set: function (value) {
  4322. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4323. },
  4324. enumerable: true,
  4325. configurable: true
  4326. });
  4327. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4328. var defines = [];
  4329. if (this.useVarianceShadowMap) {
  4330. defines.push("#define VSM");
  4331. }
  4332. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4333. var mesh = subMesh.getMesh();
  4334. var material = subMesh.getMaterial();
  4335. if (material && material.needAlphaTesting()) {
  4336. defines.push("#define ALPHATEST");
  4337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4338. attribs.push(BABYLON.VertexBuffer.UVKind);
  4339. defines.push("#define UV1");
  4340. }
  4341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4343. defines.push("#define UV2");
  4344. }
  4345. }
  4346. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4347. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4348. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4349. defines.push("#define BONES");
  4350. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4351. }
  4352. if (useInstances) {
  4353. defines.push("#define INSTANCES");
  4354. attribs.push("world0");
  4355. attribs.push("world1");
  4356. attribs.push("world2");
  4357. attribs.push("world3");
  4358. }
  4359. var join = defines.join("\n");
  4360. if (this._cachedDefines != join) {
  4361. this._cachedDefines = join;
  4362. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4363. }
  4364. return this._effect.isReady();
  4365. };
  4366. ShadowGenerator.prototype.getShadowMap = function () {
  4367. return this._shadowMap;
  4368. };
  4369. ShadowGenerator.prototype.getLight = function () {
  4370. return this._light;
  4371. };
  4372. ShadowGenerator.prototype.getTransformMatrix = function () {
  4373. var lightPosition = this._light.position;
  4374. var lightDirection = this._light.direction;
  4375. if (this._light._computeTransformedPosition()) {
  4376. lightPosition = this._light._transformedPosition;
  4377. }
  4378. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4379. this._cachedPosition = lightPosition.clone();
  4380. this._cachedDirection = lightDirection.clone();
  4381. var activeCamera = this._scene.activeCamera;
  4382. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4383. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4384. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4385. }
  4386. return this._transformMatrix;
  4387. };
  4388. ShadowGenerator.prototype.getDarkness = function () {
  4389. return this._darkness;
  4390. };
  4391. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4392. if (darkness >= 1.0)
  4393. this._darkness = 1.0;
  4394. else if (darkness <= 0.0)
  4395. this._darkness = 0.0;
  4396. else
  4397. this._darkness = darkness;
  4398. };
  4399. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4400. this._transparencyShadow = hasShadow;
  4401. };
  4402. ShadowGenerator.prototype.dispose = function () {
  4403. this._shadowMap.dispose();
  4404. };
  4405. ShadowGenerator._FILTER_NONE = 0;
  4406. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4407. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4408. return ShadowGenerator;
  4409. })();
  4410. BABYLON.ShadowGenerator = ShadowGenerator;
  4411. })(BABYLON || (BABYLON = {}));
  4412. var __extends = this.__extends || function (d, b) {
  4413. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4414. function __() { this.constructor = d; }
  4415. __.prototype = b.prototype;
  4416. d.prototype = new __();
  4417. };
  4418. var BABYLON;
  4419. (function (BABYLON) {
  4420. var HemisphericLight = (function (_super) {
  4421. __extends(HemisphericLight, _super);
  4422. function HemisphericLight(name, direction, scene) {
  4423. _super.call(this, name, scene);
  4424. this.direction = direction;
  4425. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4426. }
  4427. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4428. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4429. return this.direction;
  4430. };
  4431. HemisphericLight.prototype.getShadowGenerator = function () {
  4432. return null;
  4433. };
  4434. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4435. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4436. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4437. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4438. };
  4439. HemisphericLight.prototype._getWorldMatrix = function () {
  4440. if (!this._worldMatrix) {
  4441. this._worldMatrix = BABYLON.Matrix.Identity();
  4442. }
  4443. return this._worldMatrix;
  4444. };
  4445. return HemisphericLight;
  4446. })(BABYLON.Light);
  4447. BABYLON.HemisphericLight = HemisphericLight;
  4448. })(BABYLON || (BABYLON = {}));
  4449. var BABYLON;
  4450. (function (BABYLON) {
  4451. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4452. if (boxMin.x > sphereCenter.x + sphereRadius)
  4453. return false;
  4454. if (sphereCenter.x - sphereRadius > boxMax.x)
  4455. return false;
  4456. if (boxMin.y > sphereCenter.y + sphereRadius)
  4457. return false;
  4458. if (sphereCenter.y - sphereRadius > boxMax.y)
  4459. return false;
  4460. if (boxMin.z > sphereCenter.z + sphereRadius)
  4461. return false;
  4462. if (sphereCenter.z - sphereRadius > boxMax.z)
  4463. return false;
  4464. return true;
  4465. };
  4466. var getLowestRoot = function (a, b, c, maxR) {
  4467. var determinant = b * b - 4.0 * a * c;
  4468. var result = { root: 0, found: false };
  4469. if (determinant < 0)
  4470. return result;
  4471. var sqrtD = Math.sqrt(determinant);
  4472. var r1 = (-b - sqrtD) / (2.0 * a);
  4473. var r2 = (-b + sqrtD) / (2.0 * a);
  4474. if (r1 > r2) {
  4475. var temp = r2;
  4476. r2 = r1;
  4477. r1 = temp;
  4478. }
  4479. if (r1 > 0 && r1 < maxR) {
  4480. result.root = r1;
  4481. result.found = true;
  4482. return result;
  4483. }
  4484. if (r2 > 0 && r2 < maxR) {
  4485. result.root = r2;
  4486. result.found = true;
  4487. return result;
  4488. }
  4489. return result;
  4490. };
  4491. var Collider = (function () {
  4492. function Collider() {
  4493. this.radius = new BABYLON.Vector3(1, 1, 1);
  4494. this.retry = 0;
  4495. this.basePointWorld = BABYLON.Vector3.Zero();
  4496. this.velocityWorld = BABYLON.Vector3.Zero();
  4497. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4498. this._collisionPoint = BABYLON.Vector3.Zero();
  4499. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4500. this._tempVector = BABYLON.Vector3.Zero();
  4501. this._tempVector2 = BABYLON.Vector3.Zero();
  4502. this._tempVector3 = BABYLON.Vector3.Zero();
  4503. this._tempVector4 = BABYLON.Vector3.Zero();
  4504. this._edge = BABYLON.Vector3.Zero();
  4505. this._baseToVertex = BABYLON.Vector3.Zero();
  4506. this._destinationPoint = BABYLON.Vector3.Zero();
  4507. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4508. this._displacementVector = BABYLON.Vector3.Zero();
  4509. }
  4510. Collider.prototype._initialize = function (source, dir, e) {
  4511. this.velocity = dir;
  4512. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4513. this.basePoint = source;
  4514. source.multiplyToRef(this.radius, this.basePointWorld);
  4515. dir.multiplyToRef(this.radius, this.velocityWorld);
  4516. this.velocityWorldLength = this.velocityWorld.length();
  4517. this.epsilon = e;
  4518. this.collisionFound = false;
  4519. };
  4520. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4521. pa.subtractToRef(point, this._tempVector);
  4522. pb.subtractToRef(point, this._tempVector2);
  4523. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4524. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4525. if (d < 0)
  4526. return false;
  4527. pc.subtractToRef(point, this._tempVector3);
  4528. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4529. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4530. if (d < 0)
  4531. return false;
  4532. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4533. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4534. return d >= 0;
  4535. };
  4536. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4537. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4538. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4539. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4540. return false;
  4541. }
  4542. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4543. return false;
  4544. return true;
  4545. };
  4546. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4547. var t0;
  4548. var embeddedInPlane = false;
  4549. if (!subMesh._trianglePlanes) {
  4550. subMesh._trianglePlanes = [];
  4551. }
  4552. if (!subMesh._trianglePlanes[faceIndex]) {
  4553. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4554. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4555. }
  4556. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4557. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4558. return;
  4559. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4560. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4561. if (normalDotVelocity == 0) {
  4562. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4563. return;
  4564. embeddedInPlane = true;
  4565. t0 = 0;
  4566. } else {
  4567. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4568. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4569. if (t0 > t1) {
  4570. var temp = t1;
  4571. t1 = t0;
  4572. t0 = temp;
  4573. }
  4574. if (t0 > 1.0 || t1 < 0.0)
  4575. return;
  4576. if (t0 < 0)
  4577. t0 = 0;
  4578. if (t0 > 1.0)
  4579. t0 = 1.0;
  4580. }
  4581. this._collisionPoint.copyFromFloats(0, 0, 0);
  4582. var found = false;
  4583. var t = 1.0;
  4584. if (!embeddedInPlane) {
  4585. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4586. this.velocity.scaleToRef(t0, this._tempVector);
  4587. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4588. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4589. found = true;
  4590. t = t0;
  4591. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4592. }
  4593. }
  4594. if (!found) {
  4595. var velocitySquaredLength = this.velocity.lengthSquared();
  4596. var a = velocitySquaredLength;
  4597. this.basePoint.subtractToRef(p1, this._tempVector);
  4598. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4599. var c = this._tempVector.lengthSquared() - 1.0;
  4600. var lowestRoot = getLowestRoot(a, b, c, t);
  4601. if (lowestRoot.found) {
  4602. t = lowestRoot.root;
  4603. found = true;
  4604. this._collisionPoint.copyFrom(p1);
  4605. }
  4606. this.basePoint.subtractToRef(p2, this._tempVector);
  4607. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4608. c = this._tempVector.lengthSquared() - 1.0;
  4609. lowestRoot = getLowestRoot(a, b, c, t);
  4610. if (lowestRoot.found) {
  4611. t = lowestRoot.root;
  4612. found = true;
  4613. this._collisionPoint.copyFrom(p2);
  4614. }
  4615. this.basePoint.subtractToRef(p3, this._tempVector);
  4616. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4617. c = this._tempVector.lengthSquared() - 1.0;
  4618. lowestRoot = getLowestRoot(a, b, c, t);
  4619. if (lowestRoot.found) {
  4620. t = lowestRoot.root;
  4621. found = true;
  4622. this._collisionPoint.copyFrom(p3);
  4623. }
  4624. p2.subtractToRef(p1, this._edge);
  4625. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4626. var edgeSquaredLength = this._edge.lengthSquared();
  4627. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4628. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4629. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4630. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4631. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4632. lowestRoot = getLowestRoot(a, b, c, t);
  4633. if (lowestRoot.found) {
  4634. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4635. if (f >= 0.0 && f <= 1.0) {
  4636. t = lowestRoot.root;
  4637. found = true;
  4638. this._edge.scaleInPlace(f);
  4639. p1.addToRef(this._edge, this._collisionPoint);
  4640. }
  4641. }
  4642. p3.subtractToRef(p2, this._edge);
  4643. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4644. edgeSquaredLength = this._edge.lengthSquared();
  4645. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4646. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4647. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4648. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4649. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4650. lowestRoot = getLowestRoot(a, b, c, t);
  4651. if (lowestRoot.found) {
  4652. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4653. if (f >= 0.0 && f <= 1.0) {
  4654. t = lowestRoot.root;
  4655. found = true;
  4656. this._edge.scaleInPlace(f);
  4657. p2.addToRef(this._edge, this._collisionPoint);
  4658. }
  4659. }
  4660. p1.subtractToRef(p3, this._edge);
  4661. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4662. edgeSquaredLength = this._edge.lengthSquared();
  4663. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4664. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4665. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4666. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4667. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4668. lowestRoot = getLowestRoot(a, b, c, t);
  4669. if (lowestRoot.found) {
  4670. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4671. if (f >= 0.0 && f <= 1.0) {
  4672. t = lowestRoot.root;
  4673. found = true;
  4674. this._edge.scaleInPlace(f);
  4675. p3.addToRef(this._edge, this._collisionPoint);
  4676. }
  4677. }
  4678. }
  4679. if (found) {
  4680. var distToCollision = t * this.velocity.length();
  4681. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4682. if (!this.intersectionPoint) {
  4683. this.intersectionPoint = this._collisionPoint.clone();
  4684. } else {
  4685. this.intersectionPoint.copyFrom(this._collisionPoint);
  4686. }
  4687. this.nearestDistance = distToCollision;
  4688. this.collisionFound = true;
  4689. this.collidedMesh = subMesh.getMesh();
  4690. }
  4691. }
  4692. };
  4693. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4694. for (var i = indexStart; i < indexEnd; i += 3) {
  4695. var p1 = pts[indices[i] - decal];
  4696. var p2 = pts[indices[i + 1] - decal];
  4697. var p3 = pts[indices[i + 2] - decal];
  4698. this._testTriangle(i, subMesh, p3, p2, p1);
  4699. }
  4700. };
  4701. Collider.prototype._getResponse = function (pos, vel) {
  4702. pos.addToRef(vel, this._destinationPoint);
  4703. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4704. this.basePoint.addToRef(vel, pos);
  4705. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4706. this._slidePlaneNormal.normalize();
  4707. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4708. pos.addInPlace(this._displacementVector);
  4709. this.intersectionPoint.addInPlace(this._displacementVector);
  4710. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4711. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4712. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4713. };
  4714. return Collider;
  4715. })();
  4716. BABYLON.Collider = Collider;
  4717. })(BABYLON || (BABYLON = {}));
  4718. var __extends = this.__extends || function (d, b) {
  4719. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4720. function __() { this.constructor = d; }
  4721. __.prototype = b.prototype;
  4722. d.prototype = new __();
  4723. };
  4724. var BABYLON;
  4725. (function (BABYLON) {
  4726. var Camera = (function (_super) {
  4727. __extends(Camera, _super);
  4728. function Camera(name, position, scene) {
  4729. _super.call(this, name, scene);
  4730. this.position = position;
  4731. this.upVector = BABYLON.Vector3.Up();
  4732. this.orthoLeft = null;
  4733. this.orthoRight = null;
  4734. this.orthoBottom = null;
  4735. this.orthoTop = null;
  4736. this.fov = 0.8;
  4737. this.minZ = 1.0;
  4738. this.maxZ = 10000.0;
  4739. this.inertia = 0.9;
  4740. this.mode = Camera.PERSPECTIVE_CAMERA;
  4741. this.isIntermediate = false;
  4742. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4743. this.subCameras = [];
  4744. this.layerMask = 0xFFFFFFFF;
  4745. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4746. this._projectionMatrix = new BABYLON.Matrix();
  4747. this._postProcesses = new Array();
  4748. this._postProcessesTakenIndices = [];
  4749. scene.cameras.push(this);
  4750. if (!scene.activeCamera) {
  4751. scene.activeCamera = this;
  4752. }
  4753. }
  4754. Camera.prototype._initCache = function () {
  4755. _super.prototype._initCache.call(this);
  4756. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4757. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4758. this._cache.mode = undefined;
  4759. this._cache.minZ = undefined;
  4760. this._cache.maxZ = undefined;
  4761. this._cache.fov = undefined;
  4762. this._cache.aspectRatio = undefined;
  4763. this._cache.orthoLeft = undefined;
  4764. this._cache.orthoRight = undefined;
  4765. this._cache.orthoBottom = undefined;
  4766. this._cache.orthoTop = undefined;
  4767. this._cache.renderWidth = undefined;
  4768. this._cache.renderHeight = undefined;
  4769. };
  4770. Camera.prototype._updateCache = function (ignoreParentClass) {
  4771. if (!ignoreParentClass) {
  4772. _super.prototype._updateCache.call(this);
  4773. }
  4774. var engine = this.getEngine();
  4775. this._cache.position.copyFrom(this.position);
  4776. this._cache.upVector.copyFrom(this.upVector);
  4777. this._cache.mode = this.mode;
  4778. this._cache.minZ = this.minZ;
  4779. this._cache.maxZ = this.maxZ;
  4780. this._cache.fov = this.fov;
  4781. this._cache.aspectRatio = engine.getAspectRatio(this);
  4782. this._cache.orthoLeft = this.orthoLeft;
  4783. this._cache.orthoRight = this.orthoRight;
  4784. this._cache.orthoBottom = this.orthoBottom;
  4785. this._cache.orthoTop = this.orthoTop;
  4786. this._cache.renderWidth = engine.getRenderWidth();
  4787. this._cache.renderHeight = engine.getRenderHeight();
  4788. };
  4789. Camera.prototype._updateFromScene = function () {
  4790. this.updateCache();
  4791. this._update();
  4792. };
  4793. Camera.prototype._isSynchronized = function () {
  4794. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4795. };
  4796. Camera.prototype._isSynchronizedViewMatrix = function () {
  4797. if (!_super.prototype._isSynchronized.call(this))
  4798. return false;
  4799. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4800. };
  4801. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4802. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4803. if (!check) {
  4804. return false;
  4805. }
  4806. var engine = this.getEngine();
  4807. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4808. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4809. } else {
  4810. 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();
  4811. }
  4812. return check;
  4813. };
  4814. Camera.prototype.attachControl = function (element) {
  4815. };
  4816. Camera.prototype.detachControl = function (element) {
  4817. };
  4818. Camera.prototype._update = function () {
  4819. };
  4820. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4821. if (typeof insertAt === "undefined") { insertAt = null; }
  4822. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4823. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4824. return 0;
  4825. }
  4826. if (insertAt == null || insertAt < 0) {
  4827. this._postProcesses.push(postProcess);
  4828. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4829. return this._postProcesses.length - 1;
  4830. }
  4831. var add = 0;
  4832. if (this._postProcesses[insertAt]) {
  4833. var start = this._postProcesses.length - 1;
  4834. for (var i = start; i >= insertAt + 1; --i) {
  4835. this._postProcesses[i + 1] = this._postProcesses[i];
  4836. }
  4837. add = 1;
  4838. }
  4839. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4840. if (this._postProcessesTakenIndices[i] < insertAt) {
  4841. continue;
  4842. }
  4843. start = this._postProcessesTakenIndices.length - 1;
  4844. for (var j = start; j >= i; --j) {
  4845. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4846. }
  4847. this._postProcessesTakenIndices[i] = insertAt;
  4848. break;
  4849. }
  4850. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4851. this._postProcessesTakenIndices.push(insertAt);
  4852. }
  4853. var result = insertAt + add;
  4854. this._postProcesses[result] = postProcess;
  4855. return result;
  4856. };
  4857. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4858. if (typeof atIndices === "undefined") { atIndices = null; }
  4859. var result = [];
  4860. if (!atIndices) {
  4861. var length = this._postProcesses.length;
  4862. for (var i = 0; i < length; i++) {
  4863. if (this._postProcesses[i] !== postProcess) {
  4864. continue;
  4865. }
  4866. delete this._postProcesses[i];
  4867. var index = this._postProcessesTakenIndices.indexOf(i);
  4868. this._postProcessesTakenIndices.splice(index, 1);
  4869. }
  4870. } else {
  4871. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4872. for (i = 0; i < atIndices.length; i++) {
  4873. var foundPostProcess = this._postProcesses[atIndices[i]];
  4874. if (foundPostProcess !== postProcess) {
  4875. result.push(i);
  4876. continue;
  4877. }
  4878. delete this._postProcesses[atIndices[i]];
  4879. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4880. this._postProcessesTakenIndices.splice(index, 1);
  4881. }
  4882. }
  4883. return result;
  4884. };
  4885. Camera.prototype.getWorldMatrix = function () {
  4886. if (!this._worldMatrix) {
  4887. this._worldMatrix = BABYLON.Matrix.Identity();
  4888. }
  4889. var viewMatrix = this.getViewMatrix();
  4890. viewMatrix.invertToRef(this._worldMatrix);
  4891. return this._worldMatrix;
  4892. };
  4893. Camera.prototype._getViewMatrix = function () {
  4894. return BABYLON.Matrix.Identity();
  4895. };
  4896. Camera.prototype.getViewMatrix = function () {
  4897. this._computedViewMatrix = this._computeViewMatrix();
  4898. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4899. return this._computedViewMatrix;
  4900. }
  4901. if (!this._worldMatrix) {
  4902. this._worldMatrix = BABYLON.Matrix.Identity();
  4903. }
  4904. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4905. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4906. this._computedViewMatrix.invert();
  4907. this._currentRenderId = this.getScene().getRenderId();
  4908. return this._computedViewMatrix;
  4909. };
  4910. Camera.prototype._computeViewMatrix = function (force) {
  4911. if (!force && this._isSynchronizedViewMatrix()) {
  4912. return this._computedViewMatrix;
  4913. }
  4914. this._computedViewMatrix = this._getViewMatrix();
  4915. if (!this.parent || !this.parent.getWorldMatrix) {
  4916. this._currentRenderId = this.getScene().getRenderId();
  4917. }
  4918. return this._computedViewMatrix;
  4919. };
  4920. Camera.prototype.getProjectionMatrix = function (force) {
  4921. if (!force && this._isSynchronizedProjectionMatrix()) {
  4922. return this._projectionMatrix;
  4923. }
  4924. var engine = this.getEngine();
  4925. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4926. if (this.minZ <= 0) {
  4927. this.minZ = 0.1;
  4928. }
  4929. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4930. return this._projectionMatrix;
  4931. }
  4932. var halfWidth = engine.getRenderWidth() / 2.0;
  4933. var halfHeight = engine.getRenderHeight() / 2.0;
  4934. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4935. return this._projectionMatrix;
  4936. };
  4937. Camera.prototype.dispose = function () {
  4938. var index = this.getScene().cameras.indexOf(this);
  4939. this.getScene().cameras.splice(index, 1);
  4940. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4941. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4942. }
  4943. };
  4944. Camera.PERSPECTIVE_CAMERA = 0;
  4945. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4946. return Camera;
  4947. })(BABYLON.Node);
  4948. BABYLON.Camera = Camera;
  4949. })(BABYLON || (BABYLON = {}));
  4950. var __extends = this.__extends || function (d, b) {
  4951. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4952. function __() { this.constructor = d; }
  4953. __.prototype = b.prototype;
  4954. d.prototype = new __();
  4955. };
  4956. var BABYLON;
  4957. (function (BABYLON) {
  4958. var TargetCamera = (function (_super) {
  4959. __extends(TargetCamera, _super);
  4960. function TargetCamera(name, position, scene) {
  4961. _super.call(this, name, position, scene);
  4962. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4963. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4964. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4965. this.speed = 2.0;
  4966. this.noRotationConstraint = false;
  4967. this.lockedTarget = null;
  4968. this._currentTarget = BABYLON.Vector3.Zero();
  4969. this._viewMatrix = BABYLON.Matrix.Zero();
  4970. this._camMatrix = BABYLON.Matrix.Zero();
  4971. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4972. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4973. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4974. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4975. this._lookAtTemp = BABYLON.Matrix.Zero();
  4976. this._tempMatrix = BABYLON.Matrix.Zero();
  4977. }
  4978. TargetCamera.prototype._getLockedTargetPosition = function () {
  4979. if (!this.lockedTarget) {
  4980. return null;
  4981. }
  4982. return this.lockedTarget.position || this.lockedTarget;
  4983. };
  4984. TargetCamera.prototype._initCache = function () {
  4985. _super.prototype._initCache.call(this);
  4986. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4987. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4988. };
  4989. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4990. if (!ignoreParentClass) {
  4991. _super.prototype._updateCache.call(this);
  4992. }
  4993. var lockedTargetPosition = this._getLockedTargetPosition();
  4994. if (!lockedTargetPosition) {
  4995. this._cache.lockedTarget = null;
  4996. } else {
  4997. if (!this._cache.lockedTarget) {
  4998. this._cache.lockedTarget = lockedTargetPosition.clone();
  4999. } else {
  5000. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5001. }
  5002. }
  5003. this._cache.rotation.copyFrom(this.rotation);
  5004. };
  5005. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5006. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5007. return false;
  5008. }
  5009. var lockedTargetPosition = this._getLockedTargetPosition();
  5010. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5011. };
  5012. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5013. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5014. };
  5015. TargetCamera.prototype.setTarget = function (target) {
  5016. this.upVector.normalize();
  5017. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5018. this._camMatrix.invert();
  5019. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5020. var vDir = target.subtract(this.position);
  5021. if (vDir.x >= 0.0) {
  5022. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5023. } else {
  5024. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5025. }
  5026. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5027. if (isNaN(this.rotation.x)) {
  5028. this.rotation.x = 0;
  5029. }
  5030. if (isNaN(this.rotation.y)) {
  5031. this.rotation.y = 0;
  5032. }
  5033. if (isNaN(this.rotation.z)) {
  5034. this.rotation.z = 0;
  5035. }
  5036. };
  5037. TargetCamera.prototype.getTarget = function () {
  5038. return this._currentTarget;
  5039. };
  5040. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5041. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5042. };
  5043. TargetCamera.prototype._updatePosition = function () {
  5044. this.position.addInPlace(this.cameraDirection);
  5045. };
  5046. TargetCamera.prototype._update = function () {
  5047. var needToMove = this._decideIfNeedsToMove();
  5048. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5049. if (needToMove) {
  5050. this._updatePosition();
  5051. }
  5052. if (needToRotate) {
  5053. this.rotation.x += this.cameraRotation.x;
  5054. this.rotation.y += this.cameraRotation.y;
  5055. if (!this.noRotationConstraint) {
  5056. var limit = (Math.PI / 2) * 0.95;
  5057. if (this.rotation.x > limit)
  5058. this.rotation.x = limit;
  5059. if (this.rotation.x < -limit)
  5060. this.rotation.x = -limit;
  5061. }
  5062. }
  5063. if (needToMove) {
  5064. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5065. this.cameraDirection.x = 0;
  5066. }
  5067. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5068. this.cameraDirection.y = 0;
  5069. }
  5070. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5071. this.cameraDirection.z = 0;
  5072. }
  5073. this.cameraDirection.scaleInPlace(this.inertia);
  5074. }
  5075. if (needToRotate) {
  5076. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5077. this.cameraRotation.x = 0;
  5078. }
  5079. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5080. this.cameraRotation.y = 0;
  5081. }
  5082. this.cameraRotation.scaleInPlace(this.inertia);
  5083. }
  5084. };
  5085. TargetCamera.prototype._getViewMatrix = function () {
  5086. if (!this.lockedTarget) {
  5087. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5088. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5089. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5090. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5091. this._lookAtTemp.invert();
  5092. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5093. } else {
  5094. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5095. }
  5096. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5097. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5098. } else {
  5099. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5100. }
  5101. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5102. return this._viewMatrix;
  5103. };
  5104. return TargetCamera;
  5105. })(BABYLON.Camera);
  5106. BABYLON.TargetCamera = TargetCamera;
  5107. })(BABYLON || (BABYLON = {}));
  5108. var __extends = this.__extends || function (d, b) {
  5109. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5110. function __() { this.constructor = d; }
  5111. __.prototype = b.prototype;
  5112. d.prototype = new __();
  5113. };
  5114. var BABYLON;
  5115. (function (BABYLON) {
  5116. var FollowCamera = (function (_super) {
  5117. __extends(FollowCamera, _super);
  5118. function FollowCamera(name, position, scene) {
  5119. _super.call(this, name, position, scene);
  5120. this.radius = 12;
  5121. this.rotationOffset = 0;
  5122. this.heightOffset = 4;
  5123. this.cameraAcceleration = 0.05;
  5124. this.maxCameraSpeed = 20;
  5125. }
  5126. FollowCamera.prototype.getRadians = function (degrees) {
  5127. return degrees * Math.PI / 180;
  5128. };
  5129. FollowCamera.prototype.follow = function (cameraTarget) {
  5130. if (!cameraTarget)
  5131. return;
  5132. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5133. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5134. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5135. var dx = targetX - this.position.x;
  5136. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5137. var dz = (targetZ) - this.position.z;
  5138. var vx = dx * this.cameraAcceleration * 2;
  5139. var vy = dy * this.cameraAcceleration;
  5140. var vz = dz * this.cameraAcceleration * 2;
  5141. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5142. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5143. }
  5144. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5145. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5146. }
  5147. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5148. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5149. }
  5150. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5151. this.setTarget(cameraTarget.position);
  5152. };
  5153. FollowCamera.prototype._update = function () {
  5154. _super.prototype._update.call(this);
  5155. this.follow(this.target);
  5156. };
  5157. return FollowCamera;
  5158. })(BABYLON.TargetCamera);
  5159. BABYLON.FollowCamera = FollowCamera;
  5160. })(BABYLON || (BABYLON = {}));
  5161. var __extends = this.__extends || function (d, b) {
  5162. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5163. function __() { this.constructor = d; }
  5164. __.prototype = b.prototype;
  5165. d.prototype = new __();
  5166. };
  5167. var BABYLON;
  5168. (function (BABYLON) {
  5169. var FreeCamera = (function (_super) {
  5170. __extends(FreeCamera, _super);
  5171. function FreeCamera(name, position, scene) {
  5172. _super.call(this, name, position, scene);
  5173. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5174. this.keysUp = [38];
  5175. this.keysDown = [40];
  5176. this.keysLeft = [37];
  5177. this.keysRight = [39];
  5178. this.checkCollisions = false;
  5179. this.applyGravity = false;
  5180. this.angularSensibility = 2000.0;
  5181. this._keys = [];
  5182. this._collider = new BABYLON.Collider();
  5183. this._needMoveForGravity = true;
  5184. this._oldPosition = BABYLON.Vector3.Zero();
  5185. this._diffPosition = BABYLON.Vector3.Zero();
  5186. this._newPosition = BABYLON.Vector3.Zero();
  5187. }
  5188. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5189. var _this = this;
  5190. var previousPosition;
  5191. var engine = this.getEngine();
  5192. if (this._attachedElement) {
  5193. return;
  5194. }
  5195. this._attachedElement = element;
  5196. if (this._onMouseDown === undefined) {
  5197. this._onMouseDown = function (evt) {
  5198. previousPosition = {
  5199. x: evt.clientX,
  5200. y: evt.clientY
  5201. };
  5202. if (!noPreventDefault) {
  5203. evt.preventDefault();
  5204. }
  5205. };
  5206. this._onMouseUp = function (evt) {
  5207. previousPosition = null;
  5208. if (!noPreventDefault) {
  5209. evt.preventDefault();
  5210. }
  5211. };
  5212. this._onMouseOut = function (evt) {
  5213. previousPosition = null;
  5214. _this._keys = [];
  5215. if (!noPreventDefault) {
  5216. evt.preventDefault();
  5217. }
  5218. };
  5219. this._onMouseMove = function (evt) {
  5220. if (!previousPosition && !engine.isPointerLock) {
  5221. return;
  5222. }
  5223. var offsetX;
  5224. var offsetY;
  5225. if (!engine.isPointerLock) {
  5226. offsetX = evt.clientX - previousPosition.x;
  5227. offsetY = evt.clientY - previousPosition.y;
  5228. } else {
  5229. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5230. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5231. }
  5232. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5233. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5234. previousPosition = {
  5235. x: evt.clientX,
  5236. y: evt.clientY
  5237. };
  5238. if (!noPreventDefault) {
  5239. evt.preventDefault();
  5240. }
  5241. };
  5242. this._onKeyDown = function (evt) {
  5243. 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) {
  5244. var index = _this._keys.indexOf(evt.keyCode);
  5245. if (index === -1) {
  5246. _this._keys.push(evt.keyCode);
  5247. }
  5248. if (!noPreventDefault) {
  5249. evt.preventDefault();
  5250. }
  5251. }
  5252. };
  5253. this._onKeyUp = function (evt) {
  5254. 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) {
  5255. var index = _this._keys.indexOf(evt.keyCode);
  5256. if (index >= 0) {
  5257. _this._keys.splice(index, 1);
  5258. }
  5259. if (!noPreventDefault) {
  5260. evt.preventDefault();
  5261. }
  5262. }
  5263. };
  5264. this._onLostFocus = function () {
  5265. _this._keys = [];
  5266. };
  5267. this._reset = function () {
  5268. _this._keys = [];
  5269. previousPosition = null;
  5270. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5271. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5272. };
  5273. }
  5274. element.addEventListener("mousedown", this._onMouseDown, false);
  5275. element.addEventListener("mouseup", this._onMouseUp, false);
  5276. element.addEventListener("mouseout", this._onMouseOut, false);
  5277. element.addEventListener("mousemove", this._onMouseMove, false);
  5278. BABYLON.Tools.RegisterTopRootEvents([
  5279. { name: "keydown", handler: this._onKeyDown },
  5280. { name: "keyup", handler: this._onKeyUp },
  5281. { name: "blur", handler: this._onLostFocus }
  5282. ]);
  5283. };
  5284. FreeCamera.prototype.detachControl = function (element) {
  5285. if (this._attachedElement != element) {
  5286. return;
  5287. }
  5288. element.removeEventListener("mousedown", this._onMouseDown);
  5289. element.removeEventListener("mouseup", this._onMouseUp);
  5290. element.removeEventListener("mouseout", this._onMouseOut);
  5291. element.removeEventListener("mousemove", this._onMouseMove);
  5292. BABYLON.Tools.UnregisterTopRootEvents([
  5293. { name: "keydown", handler: this._onKeyDown },
  5294. { name: "keyup", handler: this._onKeyUp },
  5295. { name: "blur", handler: this._onLostFocus }
  5296. ]);
  5297. this._attachedElement = null;
  5298. if (this._reset) {
  5299. this._reset();
  5300. }
  5301. };
  5302. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5303. var globalPosition;
  5304. if (this.parent) {
  5305. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5306. } else {
  5307. globalPosition = this.position;
  5308. }
  5309. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5310. this._collider.radius = this.ellipsoid;
  5311. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5312. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5313. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5314. this.position.addInPlace(this._diffPosition);
  5315. if (this.onCollide) {
  5316. this.onCollide(this._collider.collidedMesh);
  5317. }
  5318. }
  5319. };
  5320. FreeCamera.prototype._checkInputs = function () {
  5321. if (!this._localDirection) {
  5322. this._localDirection = BABYLON.Vector3.Zero();
  5323. this._transformedDirection = BABYLON.Vector3.Zero();
  5324. }
  5325. for (var index = 0; index < this._keys.length; index++) {
  5326. var keyCode = this._keys[index];
  5327. var speed = this._computeLocalCameraSpeed();
  5328. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5329. this._localDirection.copyFromFloats(-speed, 0, 0);
  5330. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5331. this._localDirection.copyFromFloats(0, 0, speed);
  5332. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5333. this._localDirection.copyFromFloats(speed, 0, 0);
  5334. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5335. this._localDirection.copyFromFloats(0, 0, -speed);
  5336. }
  5337. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5338. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5339. this.cameraDirection.addInPlace(this._transformedDirection);
  5340. }
  5341. };
  5342. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5343. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5344. };
  5345. FreeCamera.prototype._updatePosition = function () {
  5346. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5347. this._collideWithWorld(this.cameraDirection);
  5348. if (this.applyGravity) {
  5349. var oldPosition = this.position;
  5350. this._collideWithWorld(this.getScene().gravity);
  5351. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5352. }
  5353. } else {
  5354. this.position.addInPlace(this.cameraDirection);
  5355. }
  5356. };
  5357. FreeCamera.prototype._update = function () {
  5358. this._checkInputs();
  5359. _super.prototype._update.call(this);
  5360. };
  5361. return FreeCamera;
  5362. })(BABYLON.TargetCamera);
  5363. BABYLON.FreeCamera = FreeCamera;
  5364. })(BABYLON || (BABYLON = {}));
  5365. var __extends = this.__extends || function (d, b) {
  5366. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5367. function __() { this.constructor = d; }
  5368. __.prototype = b.prototype;
  5369. d.prototype = new __();
  5370. };
  5371. var BABYLON;
  5372. (function (BABYLON) {
  5373. var TouchCamera = (function (_super) {
  5374. __extends(TouchCamera, _super);
  5375. function TouchCamera(name, position, scene) {
  5376. _super.call(this, name, position, scene);
  5377. this._offsetX = null;
  5378. this._offsetY = null;
  5379. this._pointerCount = 0;
  5380. this._pointerPressed = [];
  5381. this.angularSensibility = 200000.0;
  5382. this.moveSensibility = 500.0;
  5383. }
  5384. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5385. var _this = this;
  5386. var previousPosition;
  5387. if (this._attachedCanvas) {
  5388. return;
  5389. }
  5390. this._attachedCanvas = canvas;
  5391. if (this._onPointerDown === undefined) {
  5392. this._onPointerDown = function (evt) {
  5393. if (!noPreventDefault) {
  5394. evt.preventDefault();
  5395. }
  5396. _this._pointerPressed.push(evt.pointerId);
  5397. if (_this._pointerPressed.length !== 1) {
  5398. return;
  5399. }
  5400. previousPosition = {
  5401. x: evt.clientX,
  5402. y: evt.clientY
  5403. };
  5404. };
  5405. this._onPointerUp = function (evt) {
  5406. if (!noPreventDefault) {
  5407. evt.preventDefault();
  5408. }
  5409. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5410. if (index === -1) {
  5411. return;
  5412. }
  5413. _this._pointerPressed.splice(index, 1);
  5414. if (index != 0) {
  5415. return;
  5416. }
  5417. previousPosition = null;
  5418. _this._offsetX = null;
  5419. _this._offsetY = null;
  5420. };
  5421. this._onPointerMove = function (evt) {
  5422. if (!noPreventDefault) {
  5423. evt.preventDefault();
  5424. }
  5425. if (!previousPosition) {
  5426. return;
  5427. }
  5428. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5429. if (index != 0) {
  5430. return;
  5431. }
  5432. _this._offsetX = evt.clientX - previousPosition.x;
  5433. _this._offsetY = -(evt.clientY - previousPosition.y);
  5434. };
  5435. this._onLostFocus = function () {
  5436. _this._offsetX = null;
  5437. _this._offsetY = null;
  5438. };
  5439. }
  5440. canvas.addEventListener("pointerdown", this._onPointerDown);
  5441. canvas.addEventListener("pointerup", this._onPointerUp);
  5442. canvas.addEventListener("pointerout", this._onPointerUp);
  5443. canvas.addEventListener("pointermove", this._onPointerMove);
  5444. BABYLON.Tools.RegisterTopRootEvents([
  5445. { name: "blur", handler: this._onLostFocus }
  5446. ]);
  5447. };
  5448. TouchCamera.prototype.detachControl = function (canvas) {
  5449. if (this._attachedCanvas != canvas) {
  5450. return;
  5451. }
  5452. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5453. canvas.removeEventListener("pointerup", this._onPointerUp);
  5454. canvas.removeEventListener("pointerout", this._onPointerUp);
  5455. canvas.removeEventListener("pointermove", this._onPointerMove);
  5456. BABYLON.Tools.UnregisterTopRootEvents([
  5457. { name: "blur", handler: this._onLostFocus }
  5458. ]);
  5459. this._attachedCanvas = null;
  5460. };
  5461. TouchCamera.prototype._checkInputs = function () {
  5462. if (!this._offsetX) {
  5463. return;
  5464. }
  5465. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5466. if (this._pointerPressed.length > 1) {
  5467. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5468. } else {
  5469. var speed = this._computeLocalCameraSpeed();
  5470. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5471. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5472. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5473. }
  5474. };
  5475. return TouchCamera;
  5476. })(BABYLON.FreeCamera);
  5477. BABYLON.TouchCamera = TouchCamera;
  5478. })(BABYLON || (BABYLON = {}));
  5479. var __extends = this.__extends || function (d, b) {
  5480. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5481. function __() { this.constructor = d; }
  5482. __.prototype = b.prototype;
  5483. d.prototype = new __();
  5484. };
  5485. var BABYLON;
  5486. (function (BABYLON) {
  5487. var DeviceOrientationCamera = (function (_super) {
  5488. __extends(DeviceOrientationCamera, _super);
  5489. function DeviceOrientationCamera(name, position, scene) {
  5490. var _this = this;
  5491. _super.call(this, name, position, scene);
  5492. this._offsetX = null;
  5493. this._offsetY = null;
  5494. this._orientationGamma = 0;
  5495. this._orientationBeta = 0;
  5496. this._initialOrientationGamma = 0;
  5497. this._initialOrientationBeta = 0;
  5498. this.angularSensibility = 10000.0;
  5499. this.moveSensibility = 50.0;
  5500. window.addEventListener("resize", function () {
  5501. _this._initialOrientationGamma = null;
  5502. }, false);
  5503. }
  5504. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5505. var _this = this;
  5506. if (this._attachedCanvas) {
  5507. return;
  5508. }
  5509. this._attachedCanvas = canvas;
  5510. if (!this._orientationChanged) {
  5511. this._orientationChanged = function (evt) {
  5512. if (!_this._initialOrientationGamma) {
  5513. _this._initialOrientationGamma = evt.gamma;
  5514. _this._initialOrientationBeta = evt.beta;
  5515. }
  5516. _this._orientationGamma = evt.gamma;
  5517. _this._orientationBeta = evt.beta;
  5518. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5519. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5520. };
  5521. }
  5522. window.addEventListener("deviceorientation", this._orientationChanged);
  5523. };
  5524. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5525. if (this._attachedCanvas != canvas) {
  5526. return;
  5527. }
  5528. window.removeEventListener("deviceorientation", this._orientationChanged);
  5529. this._attachedCanvas = null;
  5530. this._orientationGamma = 0;
  5531. this._orientationBeta = 0;
  5532. this._initialOrientationGamma = 0;
  5533. this._initialOrientationBeta = 0;
  5534. };
  5535. DeviceOrientationCamera.prototype._checkInputs = function () {
  5536. if (!this._offsetX) {
  5537. return;
  5538. }
  5539. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5540. var speed = this._computeLocalCameraSpeed();
  5541. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5542. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5543. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5544. };
  5545. return DeviceOrientationCamera;
  5546. })(BABYLON.FreeCamera);
  5547. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5548. })(BABYLON || (BABYLON = {}));
  5549. var __extends = this.__extends || function (d, b) {
  5550. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5551. function __() { this.constructor = d; }
  5552. __.prototype = b.prototype;
  5553. d.prototype = new __();
  5554. };
  5555. var BABYLON;
  5556. (function (BABYLON) {
  5557. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5558. var ArcRotateCamera = (function (_super) {
  5559. __extends(ArcRotateCamera, _super);
  5560. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5561. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5562. this.alpha = alpha;
  5563. this.beta = beta;
  5564. this.radius = radius;
  5565. this.target = target;
  5566. this.inertialAlphaOffset = 0;
  5567. this.inertialBetaOffset = 0;
  5568. this.inertialRadiusOffset = 0;
  5569. this.lowerAlphaLimit = null;
  5570. this.upperAlphaLimit = null;
  5571. this.lowerBetaLimit = 0.01;
  5572. this.upperBetaLimit = Math.PI;
  5573. this.lowerRadiusLimit = null;
  5574. this.upperRadiusLimit = null;
  5575. this.angularSensibility = 1000.0;
  5576. this.wheelPrecision = 3.0;
  5577. this.keysUp = [38];
  5578. this.keysDown = [40];
  5579. this.keysLeft = [37];
  5580. this.keysRight = [39];
  5581. this.zoomOnFactor = 1;
  5582. this._keys = [];
  5583. this._viewMatrix = new BABYLON.Matrix();
  5584. this.checkCollisions = false;
  5585. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5586. this._collider = new BABYLON.Collider();
  5587. this._previousPosition = BABYLON.Vector3.Zero();
  5588. this._collisionVelocity = BABYLON.Vector3.Zero();
  5589. this._newPosition = BABYLON.Vector3.Zero();
  5590. this.getViewMatrix();
  5591. }
  5592. ArcRotateCamera.prototype._getTargetPosition = function () {
  5593. return this.target.position || this.target;
  5594. };
  5595. ArcRotateCamera.prototype._initCache = function () {
  5596. _super.prototype._initCache.call(this);
  5597. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5598. this._cache.alpha = undefined;
  5599. this._cache.beta = undefined;
  5600. this._cache.radius = undefined;
  5601. };
  5602. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5603. if (!ignoreParentClass) {
  5604. _super.prototype._updateCache.call(this);
  5605. }
  5606. this._cache.target.copyFrom(this._getTargetPosition());
  5607. this._cache.alpha = this.alpha;
  5608. this._cache.beta = this.beta;
  5609. this._cache.radius = this.radius;
  5610. };
  5611. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5612. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5613. return false;
  5614. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5615. };
  5616. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5617. var _this = this;
  5618. var previousPosition;
  5619. var pointerId;
  5620. if (this._attachedElement) {
  5621. return;
  5622. }
  5623. this._attachedElement = element;
  5624. var engine = this.getEngine();
  5625. if (this._onPointerDown === undefined) {
  5626. this._onPointerDown = function (evt) {
  5627. if (pointerId) {
  5628. return;
  5629. }
  5630. pointerId = evt.pointerId;
  5631. previousPosition = {
  5632. x: evt.clientX,
  5633. y: evt.clientY
  5634. };
  5635. if (!noPreventDefault) {
  5636. evt.preventDefault();
  5637. }
  5638. };
  5639. this._onPointerUp = function (evt) {
  5640. previousPosition = null;
  5641. pointerId = null;
  5642. if (!noPreventDefault) {
  5643. evt.preventDefault();
  5644. }
  5645. };
  5646. this._onPointerMove = function (evt) {
  5647. if (!previousPosition) {
  5648. return;
  5649. }
  5650. if (pointerId !== evt.pointerId) {
  5651. return;
  5652. }
  5653. var offsetX = evt.clientX - previousPosition.x;
  5654. var offsetY = evt.clientY - previousPosition.y;
  5655. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5656. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5657. previousPosition = {
  5658. x: evt.clientX,
  5659. y: evt.clientY
  5660. };
  5661. if (!noPreventDefault) {
  5662. evt.preventDefault();
  5663. }
  5664. };
  5665. this._onMouseMove = function (evt) {
  5666. if (!engine.isPointerLock) {
  5667. return;
  5668. }
  5669. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5670. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5671. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5672. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5673. if (!noPreventDefault) {
  5674. evt.preventDefault();
  5675. }
  5676. };
  5677. this._wheel = function (event) {
  5678. var delta = 0;
  5679. if (event.wheelDelta) {
  5680. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5681. } else if (event.detail) {
  5682. delta = -event.detail / _this.wheelPrecision;
  5683. }
  5684. if (delta)
  5685. _this.inertialRadiusOffset += delta;
  5686. if (event.preventDefault) {
  5687. if (!noPreventDefault) {
  5688. event.preventDefault();
  5689. }
  5690. }
  5691. };
  5692. this._onKeyDown = function (evt) {
  5693. 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) {
  5694. var index = _this._keys.indexOf(evt.keyCode);
  5695. if (index === -1) {
  5696. _this._keys.push(evt.keyCode);
  5697. }
  5698. if (evt.preventDefault) {
  5699. if (!noPreventDefault) {
  5700. evt.preventDefault();
  5701. }
  5702. }
  5703. }
  5704. };
  5705. this._onKeyUp = function (evt) {
  5706. 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) {
  5707. var index = _this._keys.indexOf(evt.keyCode);
  5708. if (index >= 0) {
  5709. _this._keys.splice(index, 1);
  5710. }
  5711. if (evt.preventDefault) {
  5712. if (!noPreventDefault) {
  5713. evt.preventDefault();
  5714. }
  5715. }
  5716. }
  5717. };
  5718. this._onLostFocus = function () {
  5719. _this._keys = [];
  5720. pointerId = null;
  5721. };
  5722. this._onGestureStart = function (e) {
  5723. if (window.MSGesture === undefined) {
  5724. return;
  5725. }
  5726. if (!_this._MSGestureHandler) {
  5727. _this._MSGestureHandler = new MSGesture();
  5728. _this._MSGestureHandler.target = element;
  5729. }
  5730. _this._MSGestureHandler.addPointer(e.pointerId);
  5731. };
  5732. this._onGesture = function (e) {
  5733. _this.radius *= e.scale;
  5734. if (e.preventDefault) {
  5735. if (!noPreventDefault) {
  5736. e.stopPropagation();
  5737. e.preventDefault();
  5738. }
  5739. }
  5740. };
  5741. this._reset = function () {
  5742. _this._keys = [];
  5743. _this.inertialAlphaOffset = 0;
  5744. _this.inertialBetaOffset = 0;
  5745. _this.inertialRadiusOffset = 0;
  5746. previousPosition = null;
  5747. pointerId = null;
  5748. };
  5749. }
  5750. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5751. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5752. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5753. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5754. element.addEventListener("mousemove", this._onMouseMove, false);
  5755. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5756. element.addEventListener("MSGestureChange", this._onGesture, false);
  5757. element.addEventListener('mousewheel', this._wheel, false);
  5758. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5759. BABYLON.Tools.RegisterTopRootEvents([
  5760. { name: "keydown", handler: this._onKeyDown },
  5761. { name: "keyup", handler: this._onKeyUp },
  5762. { name: "blur", handler: this._onLostFocus }
  5763. ]);
  5764. };
  5765. ArcRotateCamera.prototype.detachControl = function (element) {
  5766. if (this._attachedElement != element) {
  5767. return;
  5768. }
  5769. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5770. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5771. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5772. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5773. element.removeEventListener("mousemove", this._onMouseMove);
  5774. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5775. element.removeEventListener("MSGestureChange", this._onGesture);
  5776. element.removeEventListener('mousewheel', this._wheel);
  5777. element.removeEventListener('DOMMouseScroll', this._wheel);
  5778. BABYLON.Tools.UnregisterTopRootEvents([
  5779. { name: "keydown", handler: this._onKeyDown },
  5780. { name: "keyup", handler: this._onKeyUp },
  5781. { name: "blur", handler: this._onLostFocus }
  5782. ]);
  5783. this._MSGestureHandler = null;
  5784. this._attachedElement = null;
  5785. if (this._reset) {
  5786. this._reset();
  5787. }
  5788. };
  5789. ArcRotateCamera.prototype._update = function () {
  5790. for (var index = 0; index < this._keys.length; index++) {
  5791. var keyCode = this._keys[index];
  5792. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5793. this.inertialAlphaOffset -= 0.01;
  5794. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5795. this.inertialBetaOffset -= 0.01;
  5796. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5797. this.inertialAlphaOffset += 0.01;
  5798. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5799. this.inertialBetaOffset += 0.01;
  5800. }
  5801. }
  5802. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5803. this.alpha += this.inertialAlphaOffset;
  5804. this.beta += this.inertialBetaOffset;
  5805. this.radius -= this.inertialRadiusOffset;
  5806. this.inertialAlphaOffset *= this.inertia;
  5807. this.inertialBetaOffset *= this.inertia;
  5808. this.inertialRadiusOffset *= this.inertia;
  5809. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5810. this.inertialAlphaOffset = 0;
  5811. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5812. this.inertialBetaOffset = 0;
  5813. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5814. this.inertialRadiusOffset = 0;
  5815. }
  5816. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5817. this.alpha = this.lowerAlphaLimit;
  5818. }
  5819. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5820. this.alpha = this.upperAlphaLimit;
  5821. }
  5822. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5823. this.beta = this.lowerBetaLimit;
  5824. }
  5825. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5826. this.beta = this.upperBetaLimit;
  5827. }
  5828. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5829. this.radius = this.lowerRadiusLimit;
  5830. }
  5831. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5832. this.radius = this.upperRadiusLimit;
  5833. }
  5834. };
  5835. ArcRotateCamera.prototype.setPosition = function (position) {
  5836. var radiusv3 = position.subtract(this._getTargetPosition());
  5837. this.radius = radiusv3.length();
  5838. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5839. if (radiusv3.z < 0) {
  5840. this.alpha = 2 * Math.PI - this.alpha;
  5841. }
  5842. this.beta = Math.acos(radiusv3.y / this.radius);
  5843. };
  5844. ArcRotateCamera.prototype._getViewMatrix = function () {
  5845. var cosa = Math.cos(this.alpha);
  5846. var sina = Math.sin(this.alpha);
  5847. var cosb = Math.cos(this.beta);
  5848. var sinb = Math.sin(this.beta);
  5849. var target = this._getTargetPosition();
  5850. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5851. if (this.checkCollisions) {
  5852. this._collider.radius = this.collisionRadius;
  5853. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5854. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5855. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5856. this.position.copyFrom(this._previousPosition);
  5857. this.alpha = this._previousAlpha;
  5858. this.beta = this._previousBeta;
  5859. this.radius = this._previousRadius;
  5860. if (this.onCollide) {
  5861. this.onCollide(this._collider.collidedMesh);
  5862. }
  5863. }
  5864. }
  5865. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5866. this._previousAlpha = this.alpha;
  5867. this._previousBeta = this.beta;
  5868. this._previousRadius = this.radius;
  5869. this._previousPosition.copyFrom(this.position);
  5870. return this._viewMatrix;
  5871. };
  5872. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5873. meshes = meshes || this.getScene().meshes;
  5874. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5875. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5876. this.radius = distance * this.zoomOnFactor;
  5877. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5878. };
  5879. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5880. var meshesOrMinMaxVector;
  5881. var distance;
  5882. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5883. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5884. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5885. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5886. } else {
  5887. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5888. distance = meshesOrMinMaxVectorAndDistance.distance;
  5889. }
  5890. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5891. this.maxZ = distance * 2;
  5892. };
  5893. return ArcRotateCamera;
  5894. })(BABYLON.Camera);
  5895. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5896. })(BABYLON || (BABYLON = {}));
  5897. var BABYLON;
  5898. (function (BABYLON) {
  5899. var Scene = (function () {
  5900. function Scene(engine) {
  5901. this.autoClear = true;
  5902. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5903. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5904. this.forceWireframe = false;
  5905. this.cameraToUseForPointers = null;
  5906. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5907. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5908. this.fogDensity = 0.1;
  5909. this.fogStart = 0;
  5910. this.fogEnd = 1000.0;
  5911. this.lightsEnabled = true;
  5912. this.lights = new Array();
  5913. this.cameras = new Array();
  5914. this.activeCameras = new Array();
  5915. this.meshes = new Array();
  5916. this._geometries = new Array();
  5917. this.materials = new Array();
  5918. this.multiMaterials = new Array();
  5919. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5920. this.texturesEnabled = true;
  5921. this.textures = new Array();
  5922. this.particlesEnabled = true;
  5923. this.particleSystems = new Array();
  5924. this.spriteManagers = new Array();
  5925. this.layers = new Array();
  5926. this.skeletons = new Array();
  5927. this.lensFlareSystems = new Array();
  5928. this.collisionsEnabled = true;
  5929. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5930. this.postProcessesEnabled = true;
  5931. this.renderTargetsEnabled = true;
  5932. this.customRenderTargets = new Array();
  5933. this.importedMeshesFiles = new Array();
  5934. this._actionManagers = new Array();
  5935. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5936. this._totalVertices = 0;
  5937. this._activeVertices = 0;
  5938. this._activeParticles = 0;
  5939. this._lastFrameDuration = 0;
  5940. this._evaluateActiveMeshesDuration = 0;
  5941. this._renderTargetsDuration = 0;
  5942. this._particlesDuration = 0;
  5943. this._renderDuration = 0;
  5944. this._spritesDuration = 0;
  5945. this._animationRatio = 0;
  5946. this._renderId = 0;
  5947. this._executeWhenReadyTimeoutId = -1;
  5948. this._toBeDisposed = new BABYLON.SmartArray(256);
  5949. this._onReadyCallbacks = new Array();
  5950. this._pendingData = [];
  5951. this._onBeforeRenderCallbacks = new Array();
  5952. this._activeMeshes = new BABYLON.SmartArray(256);
  5953. this._processedMaterials = new BABYLON.SmartArray(256);
  5954. this._renderTargets = new BABYLON.SmartArray(256);
  5955. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5956. this._activeSkeletons = new BABYLON.SmartArray(32);
  5957. this._activeAnimatables = new Array();
  5958. this._transformMatrix = BABYLON.Matrix.Zero();
  5959. this._scaledPosition = BABYLON.Vector3.Zero();
  5960. this._scaledVelocity = BABYLON.Vector3.Zero();
  5961. this._engine = engine;
  5962. engine.scenes.push(this);
  5963. this._renderingManager = new BABYLON.RenderingManager(this);
  5964. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5965. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5966. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5967. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5968. this.attachControl();
  5969. }
  5970. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5971. get: function () {
  5972. return this._meshUnderPointer;
  5973. },
  5974. enumerable: true,
  5975. configurable: true
  5976. });
  5977. Object.defineProperty(Scene.prototype, "pointerX", {
  5978. get: function () {
  5979. return this._pointerX;
  5980. },
  5981. enumerable: true,
  5982. configurable: true
  5983. });
  5984. Object.defineProperty(Scene.prototype, "pointerY", {
  5985. get: function () {
  5986. return this._pointerY;
  5987. },
  5988. enumerable: true,
  5989. configurable: true
  5990. });
  5991. Scene.prototype.getBoundingBoxRenderer = function () {
  5992. return this._boundingBoxRenderer;
  5993. };
  5994. Scene.prototype.getOutlineRenderer = function () {
  5995. return this._outlineRenderer;
  5996. };
  5997. Scene.prototype.getEngine = function () {
  5998. return this._engine;
  5999. };
  6000. Scene.prototype.getTotalVertices = function () {
  6001. return this._totalVertices;
  6002. };
  6003. Scene.prototype.getActiveVertices = function () {
  6004. return this._activeVertices;
  6005. };
  6006. Scene.prototype.getActiveParticles = function () {
  6007. return this._activeParticles;
  6008. };
  6009. Scene.prototype.getLastFrameDuration = function () {
  6010. return this._lastFrameDuration;
  6011. };
  6012. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6013. return this._evaluateActiveMeshesDuration;
  6014. };
  6015. Scene.prototype.getActiveMeshes = function () {
  6016. return this._activeMeshes;
  6017. };
  6018. Scene.prototype.getRenderTargetsDuration = function () {
  6019. return this._renderTargetsDuration;
  6020. };
  6021. Scene.prototype.getRenderDuration = function () {
  6022. return this._renderDuration;
  6023. };
  6024. Scene.prototype.getParticlesDuration = function () {
  6025. return this._particlesDuration;
  6026. };
  6027. Scene.prototype.getSpritesDuration = function () {
  6028. return this._spritesDuration;
  6029. };
  6030. Scene.prototype.getAnimationRatio = function () {
  6031. return this._animationRatio;
  6032. };
  6033. Scene.prototype.getRenderId = function () {
  6034. return this._renderId;
  6035. };
  6036. Scene.prototype._updatePointerPosition = function (evt) {
  6037. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6038. this._pointerX = evt.clientX - canvasRect.left;
  6039. this._pointerY = evt.clientY - canvasRect.top;
  6040. if (this.cameraToUseForPointers) {
  6041. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6042. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6043. }
  6044. };
  6045. Scene.prototype.attachControl = function () {
  6046. var _this = this;
  6047. this._onPointerMove = function (evt) {
  6048. var canvas = _this._engine.getRenderingCanvas();
  6049. _this._updatePointerPosition(evt);
  6050. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6051. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6052. }, false, _this.cameraToUseForPointers);
  6053. if (pickResult.hit) {
  6054. _this._meshUnderPointer = pickResult.pickedMesh;
  6055. _this.setPointerOverMesh(pickResult.pickedMesh);
  6056. canvas.style.cursor = "pointer";
  6057. } else {
  6058. _this.setPointerOverMesh(null);
  6059. canvas.style.cursor = "";
  6060. _this._meshUnderPointer = null;
  6061. }
  6062. };
  6063. this._onPointerDown = function (evt) {
  6064. var predicate = null;
  6065. if (!_this.onPointerDown) {
  6066. predicate = function (mesh) {
  6067. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6068. };
  6069. }
  6070. _this._updatePointerPosition(evt);
  6071. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6072. if (pickResult.hit) {
  6073. if (pickResult.pickedMesh.actionManager) {
  6074. switch (evt.button) {
  6075. case 0:
  6076. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6077. break;
  6078. case 1:
  6079. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6080. break;
  6081. case 2:
  6082. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6083. break;
  6084. }
  6085. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6086. }
  6087. }
  6088. if (_this.onPointerDown) {
  6089. _this.onPointerDown(evt, pickResult);
  6090. }
  6091. };
  6092. this._onKeyDown = function (evt) {
  6093. if (_this.actionManager) {
  6094. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6095. }
  6096. };
  6097. this._onKeyUp = function (evt) {
  6098. if (_this.actionManager) {
  6099. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6100. }
  6101. };
  6102. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6103. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6104. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6105. window.addEventListener("keydown", this._onKeyDown, false);
  6106. window.addEventListener("keyup", this._onKeyUp, false);
  6107. };
  6108. Scene.prototype.detachControl = function () {
  6109. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6110. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6111. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6112. window.removeEventListener("keydown", this._onKeyDown);
  6113. window.removeEventListener("keyup", this._onKeyUp);
  6114. };
  6115. Scene.prototype.isReady = function () {
  6116. if (this._pendingData.length > 0) {
  6117. return false;
  6118. }
  6119. for (var index = 0; index < this._geometries.length; index++) {
  6120. var geometry = this._geometries[index];
  6121. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6122. return false;
  6123. }
  6124. }
  6125. for (index = 0; index < this.meshes.length; index++) {
  6126. var mesh = this.meshes[index];
  6127. if (!mesh.isReady()) {
  6128. return false;
  6129. }
  6130. var mat = mesh.material;
  6131. if (mat) {
  6132. if (!mat.isReady(mesh)) {
  6133. return false;
  6134. }
  6135. }
  6136. }
  6137. return true;
  6138. };
  6139. Scene.prototype.registerBeforeRender = function (func) {
  6140. this._onBeforeRenderCallbacks.push(func);
  6141. };
  6142. Scene.prototype.unregisterBeforeRender = function (func) {
  6143. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6144. if (index > -1) {
  6145. this._onBeforeRenderCallbacks.splice(index, 1);
  6146. }
  6147. };
  6148. Scene.prototype._addPendingData = function (data) {
  6149. this._pendingData.push(data);
  6150. };
  6151. Scene.prototype._removePendingData = function (data) {
  6152. var index = this._pendingData.indexOf(data);
  6153. if (index !== -1) {
  6154. this._pendingData.splice(index, 1);
  6155. }
  6156. };
  6157. Scene.prototype.getWaitingItemsCount = function () {
  6158. return this._pendingData.length;
  6159. };
  6160. Scene.prototype.executeWhenReady = function (func) {
  6161. var _this = this;
  6162. this._onReadyCallbacks.push(func);
  6163. if (this._executeWhenReadyTimeoutId !== -1) {
  6164. return;
  6165. }
  6166. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6167. _this._checkIsReady();
  6168. }, 150);
  6169. };
  6170. Scene.prototype._checkIsReady = function () {
  6171. var _this = this;
  6172. if (this.isReady()) {
  6173. this._onReadyCallbacks.forEach(function (func) {
  6174. func();
  6175. });
  6176. this._onReadyCallbacks = [];
  6177. this._executeWhenReadyTimeoutId = -1;
  6178. return;
  6179. }
  6180. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6181. _this._checkIsReady();
  6182. }, 150);
  6183. };
  6184. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6185. if (speedRatio === undefined) {
  6186. speedRatio = 1.0;
  6187. }
  6188. this.stopAnimation(target);
  6189. if (!animatable) {
  6190. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6191. }
  6192. if (target.animations) {
  6193. animatable.appendAnimations(target, target.animations);
  6194. }
  6195. if (target.getAnimatables) {
  6196. var animatables = target.getAnimatables();
  6197. for (var index = 0; index < animatables.length; index++) {
  6198. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6199. }
  6200. }
  6201. return animatable;
  6202. };
  6203. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6204. if (speedRatio === undefined) {
  6205. speedRatio = 1.0;
  6206. }
  6207. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6208. return animatable;
  6209. };
  6210. Scene.prototype.getAnimatableByTarget = function (target) {
  6211. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6212. if (this._activeAnimatables[index].target === target) {
  6213. return this._activeAnimatables[index];
  6214. }
  6215. }
  6216. return null;
  6217. };
  6218. Scene.prototype.stopAnimation = function (target) {
  6219. var animatable = this.getAnimatableByTarget(target);
  6220. if (animatable) {
  6221. animatable.stop();
  6222. }
  6223. };
  6224. Scene.prototype._animate = function () {
  6225. if (!this._animationStartDate) {
  6226. this._animationStartDate = new Date().getTime();
  6227. }
  6228. var now = new Date().getTime();
  6229. var delay = now - this._animationStartDate;
  6230. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6231. if (!this._activeAnimatables[index]._animate(delay)) {
  6232. this._activeAnimatables.splice(index, 1);
  6233. index--;
  6234. }
  6235. }
  6236. };
  6237. Scene.prototype.getViewMatrix = function () {
  6238. return this._viewMatrix;
  6239. };
  6240. Scene.prototype.getProjectionMatrix = function () {
  6241. return this._projectionMatrix;
  6242. };
  6243. Scene.prototype.getTransformMatrix = function () {
  6244. return this._transformMatrix;
  6245. };
  6246. Scene.prototype.setTransformMatrix = function (view, projection) {
  6247. this._viewMatrix = view;
  6248. this._projectionMatrix = projection;
  6249. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6250. };
  6251. Scene.prototype.setActiveCameraByID = function (id) {
  6252. var camera = this.getCameraByID(id);
  6253. if (camera) {
  6254. this.activeCamera = camera;
  6255. return camera;
  6256. }
  6257. return null;
  6258. };
  6259. Scene.prototype.setActiveCameraByName = function (name) {
  6260. var camera = this.getCameraByName(name);
  6261. if (camera) {
  6262. this.activeCamera = camera;
  6263. return camera;
  6264. }
  6265. return null;
  6266. };
  6267. Scene.prototype.getMaterialByID = function (id) {
  6268. for (var index = 0; index < this.materials.length; index++) {
  6269. if (this.materials[index].id === id) {
  6270. return this.materials[index];
  6271. }
  6272. }
  6273. return null;
  6274. };
  6275. Scene.prototype.getMaterialByName = function (name) {
  6276. for (var index = 0; index < this.materials.length; index++) {
  6277. if (this.materials[index].name === name) {
  6278. return this.materials[index];
  6279. }
  6280. }
  6281. return null;
  6282. };
  6283. Scene.prototype.getCameraByID = function (id) {
  6284. for (var index = 0; index < this.cameras.length; index++) {
  6285. if (this.cameras[index].id === id) {
  6286. return this.cameras[index];
  6287. }
  6288. }
  6289. return null;
  6290. };
  6291. Scene.prototype.getCameraByName = function (name) {
  6292. for (var index = 0; index < this.cameras.length; index++) {
  6293. if (this.cameras[index].name === name) {
  6294. return this.cameras[index];
  6295. }
  6296. }
  6297. return null;
  6298. };
  6299. Scene.prototype.getLightByName = function (name) {
  6300. for (var index = 0; index < this.lights.length; index++) {
  6301. if (this.lights[index].name === name) {
  6302. return this.lights[index];
  6303. }
  6304. }
  6305. return null;
  6306. };
  6307. Scene.prototype.getLightByID = function (id) {
  6308. for (var index = 0; index < this.lights.length; index++) {
  6309. if (this.lights[index].id === id) {
  6310. return this.lights[index];
  6311. }
  6312. }
  6313. return null;
  6314. };
  6315. Scene.prototype.getGeometryByID = function (id) {
  6316. for (var index = 0; index < this._geometries.length; index++) {
  6317. if (this._geometries[index].id === id) {
  6318. return this._geometries[index];
  6319. }
  6320. }
  6321. return null;
  6322. };
  6323. Scene.prototype.pushGeometry = function (geometry, force) {
  6324. if (!force && this.getGeometryByID(geometry.id)) {
  6325. return false;
  6326. }
  6327. this._geometries.push(geometry);
  6328. return true;
  6329. };
  6330. Scene.prototype.getGeometries = function () {
  6331. return this._geometries;
  6332. };
  6333. Scene.prototype.getMeshByID = function (id) {
  6334. for (var index = 0; index < this.meshes.length; index++) {
  6335. if (this.meshes[index].id === id) {
  6336. return this.meshes[index];
  6337. }
  6338. }
  6339. return null;
  6340. };
  6341. Scene.prototype.getLastMeshByID = function (id) {
  6342. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6343. if (this.meshes[index].id === id) {
  6344. return this.meshes[index];
  6345. }
  6346. }
  6347. return null;
  6348. };
  6349. Scene.prototype.getLastEntryByID = function (id) {
  6350. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6351. if (this.meshes[index].id === id) {
  6352. return this.meshes[index];
  6353. }
  6354. }
  6355. for (index = this.cameras.length - 1; index >= 0; index--) {
  6356. if (this.cameras[index].id === id) {
  6357. return this.cameras[index];
  6358. }
  6359. }
  6360. for (index = this.lights.length - 1; index >= 0; index--) {
  6361. if (this.lights[index].id === id) {
  6362. return this.lights[index];
  6363. }
  6364. }
  6365. return null;
  6366. };
  6367. Scene.prototype.getMeshByName = function (name) {
  6368. for (var index = 0; index < this.meshes.length; index++) {
  6369. if (this.meshes[index].name === name) {
  6370. return this.meshes[index];
  6371. }
  6372. }
  6373. return null;
  6374. };
  6375. Scene.prototype.getLastSkeletonByID = function (id) {
  6376. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6377. if (this.skeletons[index].id === id) {
  6378. return this.skeletons[index];
  6379. }
  6380. }
  6381. return null;
  6382. };
  6383. Scene.prototype.getSkeletonById = function (id) {
  6384. for (var index = 0; index < this.skeletons.length; index++) {
  6385. if (this.skeletons[index].id === id) {
  6386. return this.skeletons[index];
  6387. }
  6388. }
  6389. return null;
  6390. };
  6391. Scene.prototype.getSkeletonByName = function (name) {
  6392. for (var index = 0; index < this.skeletons.length; index++) {
  6393. if (this.skeletons[index].name === name) {
  6394. return this.skeletons[index];
  6395. }
  6396. }
  6397. return null;
  6398. };
  6399. Scene.prototype.isActiveMesh = function (mesh) {
  6400. return (this._activeMeshes.indexOf(mesh) !== -1);
  6401. };
  6402. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6403. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6404. var material = subMesh.getMaterial();
  6405. if (mesh.showSubMeshesBoundingBox) {
  6406. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6407. }
  6408. if (material) {
  6409. if (material.getRenderTargetTextures) {
  6410. if (this._processedMaterials.indexOf(material) === -1) {
  6411. this._processedMaterials.push(material);
  6412. this._renderTargets.concat(material.getRenderTargetTextures());
  6413. }
  6414. }
  6415. this._activeVertices += subMesh.verticesCount;
  6416. this._renderingManager.dispatch(subMesh);
  6417. }
  6418. }
  6419. };
  6420. Scene.prototype._evaluateActiveMeshes = function () {
  6421. this._activeMeshes.reset();
  6422. this._renderingManager.reset();
  6423. this._processedMaterials.reset();
  6424. this._activeParticleSystems.reset();
  6425. this._activeSkeletons.reset();
  6426. this._boundingBoxRenderer.reset();
  6427. if (!this._frustumPlanes) {
  6428. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6429. } else {
  6430. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6431. }
  6432. var meshes;
  6433. var len;
  6434. if (this._selectionOctree) {
  6435. var selection = this._selectionOctree.select(this._frustumPlanes);
  6436. meshes = selection.data;
  6437. len = selection.length;
  6438. } else {
  6439. len = this.meshes.length;
  6440. meshes = this.meshes;
  6441. }
  6442. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6443. var mesh = meshes[meshIndex];
  6444. this._totalVertices += mesh.getTotalVertices();
  6445. if (!mesh.isReady()) {
  6446. continue;
  6447. }
  6448. mesh.computeWorldMatrix();
  6449. mesh._preActivate();
  6450. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6451. this._meshesForIntersections.pushNoDuplicate(mesh);
  6452. }
  6453. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6454. this._activeMeshes.push(mesh);
  6455. mesh._activate(this._renderId);
  6456. this._activeMesh(mesh);
  6457. }
  6458. }
  6459. var beforeParticlesDate = new Date().getTime();
  6460. if (this.particlesEnabled) {
  6461. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6462. var particleSystem = this.particleSystems[particleIndex];
  6463. if (!particleSystem.isStarted()) {
  6464. continue;
  6465. }
  6466. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6467. this._activeParticleSystems.push(particleSystem);
  6468. particleSystem.animate();
  6469. }
  6470. }
  6471. }
  6472. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6473. };
  6474. Scene.prototype._activeMesh = function (mesh) {
  6475. if (mesh.skeleton) {
  6476. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6477. }
  6478. if (mesh.showBoundingBox) {
  6479. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6480. }
  6481. if (mesh.subMeshes) {
  6482. var len;
  6483. var subMeshes;
  6484. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6485. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6486. len = intersections.length;
  6487. subMeshes = intersections.data;
  6488. } else {
  6489. subMeshes = mesh.subMeshes;
  6490. len = subMeshes.length;
  6491. }
  6492. for (var subIndex = 0; subIndex < len; subIndex++) {
  6493. var subMesh = subMeshes[subIndex];
  6494. this._evaluateSubMesh(subMesh, mesh);
  6495. }
  6496. }
  6497. };
  6498. Scene.prototype.updateTransformMatrix = function (force) {
  6499. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6500. };
  6501. Scene.prototype._renderForCamera = function (camera) {
  6502. var engine = this._engine;
  6503. this.activeCamera = camera;
  6504. if (!this.activeCamera)
  6505. throw new Error("Active camera not set");
  6506. engine.setViewport(this.activeCamera.viewport);
  6507. this._renderId++;
  6508. this.updateTransformMatrix();
  6509. if (this.beforeCameraRender) {
  6510. this.beforeCameraRender(this.activeCamera);
  6511. }
  6512. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6513. this._evaluateActiveMeshes();
  6514. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6515. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6516. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6517. skeleton.prepare();
  6518. }
  6519. var beforeRenderTargetDate = new Date().getTime();
  6520. if (this.renderTargetsEnabled) {
  6521. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6522. var renderTarget = this._renderTargets.data[renderIndex];
  6523. if (renderTarget._shouldRender()) {
  6524. this._renderId++;
  6525. renderTarget.render();
  6526. }
  6527. }
  6528. this._renderId++;
  6529. }
  6530. if (this._renderTargets.length > 0) {
  6531. engine.restoreDefaultFramebuffer();
  6532. }
  6533. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6534. this.postProcessManager._prepareFrame();
  6535. var beforeRenderDate = new Date().getTime();
  6536. if (this.layers.length) {
  6537. engine.setDepthBuffer(false);
  6538. var layerIndex;
  6539. var layer;
  6540. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6541. layer = this.layers[layerIndex];
  6542. if (layer.isBackground) {
  6543. layer.render();
  6544. }
  6545. }
  6546. engine.setDepthBuffer(true);
  6547. }
  6548. this._renderingManager.render(null, null, true, true);
  6549. this._boundingBoxRenderer.render();
  6550. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6551. this.lensFlareSystems[lensFlareSystemIndex].render();
  6552. }
  6553. if (this.layers.length) {
  6554. engine.setDepthBuffer(false);
  6555. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6556. layer = this.layers[layerIndex];
  6557. if (!layer.isBackground) {
  6558. layer.render();
  6559. }
  6560. }
  6561. engine.setDepthBuffer(true);
  6562. }
  6563. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6564. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6565. this.activeCamera._updateFromScene();
  6566. this._renderTargets.reset();
  6567. if (this.afterCameraRender) {
  6568. this.afterCameraRender(this.activeCamera);
  6569. }
  6570. };
  6571. Scene.prototype._processSubCameras = function (camera) {
  6572. if (camera.subCameras.length == 0) {
  6573. this._renderForCamera(camera);
  6574. return;
  6575. }
  6576. for (var index = 0; index < camera.subCameras.length; index++) {
  6577. this._renderForCamera(camera.subCameras[index]);
  6578. }
  6579. this.activeCamera = camera;
  6580. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6581. this.activeCamera._updateFromScene();
  6582. };
  6583. Scene.prototype._checkIntersections = function () {
  6584. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6585. var sourceMesh = this._meshesForIntersections.data[index];
  6586. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6587. var action = sourceMesh.actionManager.actions[actionIndex];
  6588. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6589. var otherMesh = action.getTriggerParameter();
  6590. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6591. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6592. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6593. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6594. sourceMesh._intersectionsInProgress.push(otherMesh);
  6595. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6596. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6597. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6598. if (indexOfOther > -1) {
  6599. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6600. }
  6601. }
  6602. }
  6603. }
  6604. }
  6605. };
  6606. Scene.prototype.render = function () {
  6607. var startDate = new Date().getTime();
  6608. this._particlesDuration = 0;
  6609. this._spritesDuration = 0;
  6610. this._activeParticles = 0;
  6611. this._renderDuration = 0;
  6612. this._evaluateActiveMeshesDuration = 0;
  6613. this._totalVertices = 0;
  6614. this._activeVertices = 0;
  6615. this._meshesForIntersections.reset();
  6616. if (this.actionManager) {
  6617. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6618. }
  6619. if (this.beforeRender) {
  6620. this.beforeRender();
  6621. }
  6622. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6623. this._onBeforeRenderCallbacks[callbackIndex]();
  6624. }
  6625. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6626. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6627. this._animate();
  6628. if (this._physicsEngine) {
  6629. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6630. }
  6631. var beforeRenderTargetDate = new Date().getTime();
  6632. var engine = this.getEngine();
  6633. if (this.renderTargetsEnabled) {
  6634. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6635. var renderTarget = this.customRenderTargets[customIndex];
  6636. if (renderTarget._shouldRender()) {
  6637. this._renderId++;
  6638. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6639. if (!this.activeCamera)
  6640. throw new Error("Active camera not set");
  6641. engine.setViewport(this.activeCamera.viewport);
  6642. this.updateTransformMatrix();
  6643. renderTarget.render();
  6644. }
  6645. }
  6646. this._renderId++;
  6647. }
  6648. if (this.customRenderTargets.length > 0) {
  6649. engine.restoreDefaultFramebuffer();
  6650. }
  6651. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6652. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6653. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6654. var light = this.lights[lightIndex];
  6655. var shadowGenerator = light.getShadowGenerator();
  6656. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6657. this._renderTargets.push(shadowGenerator.getShadowMap());
  6658. }
  6659. }
  6660. this.postProcessRenderPipelineManager.update();
  6661. if (this.activeCameras.length > 0) {
  6662. var currentRenderId = this._renderId;
  6663. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6664. this._renderId = currentRenderId;
  6665. this._processSubCameras(this.activeCameras[cameraIndex]);
  6666. }
  6667. } else {
  6668. if (!this.activeCamera) {
  6669. throw new Error("No camera defined");
  6670. }
  6671. this._processSubCameras(this.activeCamera);
  6672. }
  6673. this._checkIntersections();
  6674. if (this.afterRender) {
  6675. this.afterRender();
  6676. }
  6677. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6678. this._toBeDisposed.data[index].dispose();
  6679. this._toBeDisposed[index] = null;
  6680. }
  6681. this._toBeDisposed.reset();
  6682. this._lastFrameDuration = new Date().getTime() - startDate;
  6683. };
  6684. Scene.prototype.dispose = function () {
  6685. this.beforeRender = null;
  6686. this.afterRender = null;
  6687. this.skeletons = [];
  6688. this._boundingBoxRenderer.dispose();
  6689. if (this.onDispose) {
  6690. this.onDispose();
  6691. }
  6692. this.detachControl();
  6693. var canvas = this._engine.getRenderingCanvas();
  6694. var index;
  6695. for (index = 0; index < this.cameras.length; index++) {
  6696. this.cameras[index].detachControl(canvas);
  6697. }
  6698. while (this.lights.length) {
  6699. this.lights[0].dispose();
  6700. }
  6701. while (this.meshes.length) {
  6702. this.meshes[0].dispose(true);
  6703. }
  6704. while (this.cameras.length) {
  6705. this.cameras[0].dispose();
  6706. }
  6707. while (this.materials.length) {
  6708. this.materials[0].dispose();
  6709. }
  6710. while (this.particleSystems.length) {
  6711. this.particleSystems[0].dispose();
  6712. }
  6713. while (this.spriteManagers.length) {
  6714. this.spriteManagers[0].dispose();
  6715. }
  6716. while (this.layers.length) {
  6717. this.layers[0].dispose();
  6718. }
  6719. while (this.textures.length) {
  6720. this.textures[0].dispose();
  6721. }
  6722. this.postProcessManager.dispose();
  6723. if (this._physicsEngine) {
  6724. this.disablePhysicsEngine();
  6725. }
  6726. index = this._engine.scenes.indexOf(this);
  6727. if (index > -1) {
  6728. this._engine.scenes.splice(index, 1);
  6729. }
  6730. this._engine.wipeCaches();
  6731. };
  6732. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6733. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6734. position.divideToRef(collider.radius, this._scaledPosition);
  6735. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6736. collider.retry = 0;
  6737. collider.initialVelocity = this._scaledVelocity;
  6738. collider.initialPosition = this._scaledPosition;
  6739. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6740. finalPosition.multiplyInPlace(collider.radius);
  6741. };
  6742. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6743. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6744. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6745. if (collider.retry >= maximumRetry) {
  6746. finalPosition.copyFrom(position);
  6747. return;
  6748. }
  6749. collider._initialize(position, velocity, closeDistance);
  6750. for (var index = 0; index < this.meshes.length; index++) {
  6751. var mesh = this.meshes[index];
  6752. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6753. mesh._checkCollision(collider);
  6754. }
  6755. }
  6756. if (!collider.collisionFound) {
  6757. position.addToRef(velocity, finalPosition);
  6758. return;
  6759. }
  6760. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6761. collider._getResponse(position, velocity);
  6762. }
  6763. if (velocity.length() <= closeDistance) {
  6764. finalPosition.copyFrom(position);
  6765. return;
  6766. }
  6767. collider.retry++;
  6768. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6769. };
  6770. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6771. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6772. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6773. if (!this._selectionOctree) {
  6774. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6775. }
  6776. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6777. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6778. for (var index = 0; index < this.meshes.length; index++) {
  6779. var mesh = this.meshes[index];
  6780. mesh.computeWorldMatrix(true);
  6781. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6782. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6783. BABYLON.Tools.CheckExtends(minBox, min, max);
  6784. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6785. }
  6786. this._selectionOctree.update(min, max, this.meshes);
  6787. return this._selectionOctree;
  6788. };
  6789. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6790. var engine = this._engine;
  6791. if (!camera) {
  6792. if (!this.activeCamera)
  6793. throw new Error("Active camera not set");
  6794. camera = this.activeCamera;
  6795. }
  6796. var cameraViewport = camera.viewport;
  6797. var viewport = cameraViewport.toGlobal(engine);
  6798. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6799. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6800. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6801. };
  6802. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6803. var pickingInfo = null;
  6804. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6805. var mesh = this.meshes[meshIndex];
  6806. if (predicate) {
  6807. if (!predicate(mesh)) {
  6808. continue;
  6809. }
  6810. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6811. continue;
  6812. }
  6813. var world = mesh.getWorldMatrix();
  6814. var ray = rayFunction(world);
  6815. var result = mesh.intersects(ray, fastCheck);
  6816. if (!result || !result.hit)
  6817. continue;
  6818. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6819. continue;
  6820. pickingInfo = result;
  6821. if (fastCheck) {
  6822. break;
  6823. }
  6824. }
  6825. return pickingInfo || new BABYLON.PickingInfo();
  6826. };
  6827. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6828. var _this = this;
  6829. return this._internalPick(function (world) {
  6830. return _this.createPickingRay(x, y, world, camera);
  6831. }, predicate, fastCheck);
  6832. };
  6833. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6834. var _this = this;
  6835. return this._internalPick(function (world) {
  6836. if (!_this._pickWithRayInverseMatrix) {
  6837. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6838. }
  6839. world.invertToRef(_this._pickWithRayInverseMatrix);
  6840. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6841. }, predicate, fastCheck);
  6842. };
  6843. Scene.prototype.setPointerOverMesh = function (mesh) {
  6844. if (this._pointerOverMesh === mesh) {
  6845. return;
  6846. }
  6847. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6848. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6849. }
  6850. this._pointerOverMesh = mesh;
  6851. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6852. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6853. }
  6854. };
  6855. Scene.prototype.getPointerOverMesh = function () {
  6856. return this._pointerOverMesh;
  6857. };
  6858. Scene.prototype.getPhysicsEngine = function () {
  6859. return this._physicsEngine;
  6860. };
  6861. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6862. if (this._physicsEngine) {
  6863. return true;
  6864. }
  6865. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6866. if (!this._physicsEngine.isSupported()) {
  6867. this._physicsEngine = null;
  6868. return false;
  6869. }
  6870. this._physicsEngine._initialize(gravity);
  6871. return true;
  6872. };
  6873. Scene.prototype.disablePhysicsEngine = function () {
  6874. if (!this._physicsEngine) {
  6875. return;
  6876. }
  6877. this._physicsEngine.dispose();
  6878. this._physicsEngine = undefined;
  6879. };
  6880. Scene.prototype.isPhysicsEnabled = function () {
  6881. return this._physicsEngine !== undefined;
  6882. };
  6883. Scene.prototype.setGravity = function (gravity) {
  6884. if (!this._physicsEngine) {
  6885. return;
  6886. }
  6887. this._physicsEngine._setGravity(gravity);
  6888. };
  6889. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6890. if (parts.parts) {
  6891. options = parts;
  6892. parts = parts.parts;
  6893. }
  6894. if (!this._physicsEngine) {
  6895. return null;
  6896. }
  6897. for (var index = 0; index < parts.length; index++) {
  6898. var mesh = parts[index].mesh;
  6899. mesh._physicImpostor = parts[index].impostor;
  6900. mesh._physicsMass = options.mass / parts.length;
  6901. mesh._physicsFriction = options.friction;
  6902. mesh._physicRestitution = options.restitution;
  6903. }
  6904. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6905. };
  6906. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6907. for (var index = 0; index < compound.parts.length; index++) {
  6908. var mesh = compound.parts[index].mesh;
  6909. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6910. this._physicsEngine._unregisterMesh(mesh);
  6911. }
  6912. };
  6913. Scene.prototype._getByTags = function (list, tagsQuery) {
  6914. if (tagsQuery === undefined) {
  6915. return list;
  6916. }
  6917. var listByTags = [];
  6918. for (var i in list) {
  6919. var item = list[i];
  6920. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6921. listByTags.push(item);
  6922. }
  6923. }
  6924. return listByTags;
  6925. };
  6926. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6927. return this._getByTags(this.meshes, tagsQuery);
  6928. };
  6929. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6930. return this._getByTags(this.cameras, tagsQuery);
  6931. };
  6932. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6933. return this._getByTags(this.lights, tagsQuery);
  6934. };
  6935. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6936. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6937. };
  6938. Scene.FOGMODE_NONE = 0;
  6939. Scene.FOGMODE_EXP = 1;
  6940. Scene.FOGMODE_EXP2 = 2;
  6941. Scene.FOGMODE_LINEAR = 3;
  6942. Scene.MinDeltaTime = 1.0;
  6943. Scene.MaxDeltaTime = 1000.0;
  6944. return Scene;
  6945. })();
  6946. BABYLON.Scene = Scene;
  6947. })(BABYLON || (BABYLON = {}));
  6948. var BABYLON;
  6949. (function (BABYLON) {
  6950. var VertexBuffer = (function () {
  6951. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6952. if (engine instanceof BABYLON.Mesh) {
  6953. this._engine = engine.getScene().getEngine();
  6954. } else {
  6955. this._engine = engine;
  6956. }
  6957. this._updatable = updatable;
  6958. this._data = data;
  6959. if (!postponeInternalCreation) {
  6960. this.create();
  6961. }
  6962. this._kind = kind;
  6963. switch (kind) {
  6964. case VertexBuffer.PositionKind:
  6965. this._strideSize = 3;
  6966. break;
  6967. case VertexBuffer.NormalKind:
  6968. this._strideSize = 3;
  6969. break;
  6970. case VertexBuffer.UVKind:
  6971. this._strideSize = 2;
  6972. break;
  6973. case VertexBuffer.UV2Kind:
  6974. this._strideSize = 2;
  6975. break;
  6976. case VertexBuffer.ColorKind:
  6977. this._strideSize = 3;
  6978. break;
  6979. case VertexBuffer.MatricesIndicesKind:
  6980. this._strideSize = 4;
  6981. break;
  6982. case VertexBuffer.MatricesWeightsKind:
  6983. this._strideSize = 4;
  6984. break;
  6985. }
  6986. }
  6987. VertexBuffer.prototype.isUpdatable = function () {
  6988. return this._updatable;
  6989. };
  6990. VertexBuffer.prototype.getData = function () {
  6991. return this._data;
  6992. };
  6993. VertexBuffer.prototype.getBuffer = function () {
  6994. return this._buffer;
  6995. };
  6996. VertexBuffer.prototype.getStrideSize = function () {
  6997. return this._strideSize;
  6998. };
  6999. VertexBuffer.prototype.create = function (data) {
  7000. if (!data && this._buffer) {
  7001. return;
  7002. }
  7003. data = data || this._data;
  7004. if (!this._buffer) {
  7005. if (this._updatable) {
  7006. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7007. } else {
  7008. this._buffer = this._engine.createVertexBuffer(data);
  7009. }
  7010. }
  7011. if (this._updatable) {
  7012. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7013. this._data = data;
  7014. }
  7015. };
  7016. VertexBuffer.prototype.update = function (data) {
  7017. this.create(data);
  7018. };
  7019. VertexBuffer.prototype.dispose = function () {
  7020. if (!this._buffer) {
  7021. return;
  7022. }
  7023. if (this._engine._releaseBuffer(this._buffer)) {
  7024. this._buffer = null;
  7025. }
  7026. };
  7027. Object.defineProperty(VertexBuffer, "PositionKind", {
  7028. get: function () {
  7029. return VertexBuffer._PositionKind;
  7030. },
  7031. enumerable: true,
  7032. configurable: true
  7033. });
  7034. Object.defineProperty(VertexBuffer, "NormalKind", {
  7035. get: function () {
  7036. return VertexBuffer._NormalKind;
  7037. },
  7038. enumerable: true,
  7039. configurable: true
  7040. });
  7041. Object.defineProperty(VertexBuffer, "UVKind", {
  7042. get: function () {
  7043. return VertexBuffer._UVKind;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7049. get: function () {
  7050. return VertexBuffer._UV2Kind;
  7051. },
  7052. enumerable: true,
  7053. configurable: true
  7054. });
  7055. Object.defineProperty(VertexBuffer, "ColorKind", {
  7056. get: function () {
  7057. return VertexBuffer._ColorKind;
  7058. },
  7059. enumerable: true,
  7060. configurable: true
  7061. });
  7062. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7063. get: function () {
  7064. return VertexBuffer._MatricesIndicesKind;
  7065. },
  7066. enumerable: true,
  7067. configurable: true
  7068. });
  7069. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7070. get: function () {
  7071. return VertexBuffer._MatricesWeightsKind;
  7072. },
  7073. enumerable: true,
  7074. configurable: true
  7075. });
  7076. VertexBuffer._PositionKind = "position";
  7077. VertexBuffer._NormalKind = "normal";
  7078. VertexBuffer._UVKind = "uv";
  7079. VertexBuffer._UV2Kind = "uv2";
  7080. VertexBuffer._ColorKind = "color";
  7081. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7082. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7083. return VertexBuffer;
  7084. })();
  7085. BABYLON.VertexBuffer = VertexBuffer;
  7086. })(BABYLON || (BABYLON = {}));
  7087. var __extends = this.__extends || function (d, b) {
  7088. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7089. function __() { this.constructor = d; }
  7090. __.prototype = b.prototype;
  7091. d.prototype = new __();
  7092. };
  7093. var BABYLON;
  7094. (function (BABYLON) {
  7095. var AbstractMesh = (function (_super) {
  7096. __extends(AbstractMesh, _super);
  7097. function AbstractMesh(name, scene) {
  7098. _super.call(this, name, scene);
  7099. this.position = new BABYLON.Vector3(0, 0, 0);
  7100. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7101. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7102. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7103. this.visibility = 1.0;
  7104. this.infiniteDistance = false;
  7105. this.isVisible = true;
  7106. this.isPickable = true;
  7107. this.showBoundingBox = false;
  7108. this.showSubMeshesBoundingBox = false;
  7109. this.onDispose = null;
  7110. this.checkCollisions = false;
  7111. this.isBlocker = false;
  7112. this.renderingGroupId = 0;
  7113. this.receiveShadows = false;
  7114. this.renderOutline = false;
  7115. this.outlineColor = BABYLON.Color3.Red();
  7116. this.outlineWidth = 0.02;
  7117. this.useOctreeForRenderingSelection = true;
  7118. this.useOctreeForPicking = true;
  7119. this.useOctreeForCollisions = true;
  7120. this.layerMask = 0xFFFFFFFF;
  7121. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7122. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7123. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7124. this._collider = new BABYLON.Collider();
  7125. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7126. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7127. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7128. this._localScaling = BABYLON.Matrix.Zero();
  7129. this._localRotation = BABYLON.Matrix.Zero();
  7130. this._localTranslation = BABYLON.Matrix.Zero();
  7131. this._localBillboard = BABYLON.Matrix.Zero();
  7132. this._localPivotScaling = BABYLON.Matrix.Zero();
  7133. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7134. this._localWorld = BABYLON.Matrix.Zero();
  7135. this._worldMatrix = BABYLON.Matrix.Zero();
  7136. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7137. this._absolutePosition = BABYLON.Vector3.Zero();
  7138. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7139. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7140. this._isDirty = false;
  7141. this._pivotMatrix = BABYLON.Matrix.Identity();
  7142. this._isDisposed = false;
  7143. this._renderId = 0;
  7144. this._intersectionsInProgress = new Array();
  7145. scene.meshes.push(this);
  7146. }
  7147. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7148. get: function () {
  7149. return AbstractMesh._BILLBOARDMODE_NONE;
  7150. },
  7151. enumerable: true,
  7152. configurable: true
  7153. });
  7154. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7155. get: function () {
  7156. return AbstractMesh._BILLBOARDMODE_X;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7162. get: function () {
  7163. return AbstractMesh._BILLBOARDMODE_Y;
  7164. },
  7165. enumerable: true,
  7166. configurable: true
  7167. });
  7168. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7169. get: function () {
  7170. return AbstractMesh._BILLBOARDMODE_Z;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7176. get: function () {
  7177. return AbstractMesh._BILLBOARDMODE_ALL;
  7178. },
  7179. enumerable: true,
  7180. configurable: true
  7181. });
  7182. AbstractMesh.prototype.getTotalVertices = function () {
  7183. return 0;
  7184. };
  7185. AbstractMesh.prototype.getIndices = function () {
  7186. return null;
  7187. };
  7188. AbstractMesh.prototype.getVerticesData = function (kind) {
  7189. return null;
  7190. };
  7191. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7192. return false;
  7193. };
  7194. AbstractMesh.prototype.getBoundingInfo = function () {
  7195. if (!this._boundingInfo) {
  7196. this._updateBoundingInfo();
  7197. }
  7198. return this._boundingInfo;
  7199. };
  7200. AbstractMesh.prototype._preActivate = function () {
  7201. };
  7202. AbstractMesh.prototype._activate = function (renderId) {
  7203. this._renderId = renderId;
  7204. };
  7205. AbstractMesh.prototype.getWorldMatrix = function () {
  7206. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7207. this.computeWorldMatrix();
  7208. }
  7209. return this._worldMatrix;
  7210. };
  7211. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7212. get: function () {
  7213. return this._worldMatrix;
  7214. },
  7215. enumerable: true,
  7216. configurable: true
  7217. });
  7218. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7219. get: function () {
  7220. return this._absolutePosition;
  7221. },
  7222. enumerable: true,
  7223. configurable: true
  7224. });
  7225. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7226. if (!this.rotationQuaternion) {
  7227. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7228. this.rotation = BABYLON.Vector3.Zero();
  7229. }
  7230. if (!space || space == 0 /* LOCAL */) {
  7231. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7232. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7233. } else {
  7234. if (this.parent) {
  7235. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7236. invertParentWorldMatrix.invert();
  7237. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7238. }
  7239. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7240. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7241. }
  7242. };
  7243. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7244. var displacementVector = axis.scale(distance);
  7245. if (!space || space == 0 /* LOCAL */) {
  7246. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7247. this.setPositionWithLocalVector(tempV3);
  7248. } else {
  7249. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7250. }
  7251. };
  7252. AbstractMesh.prototype.getAbsolutePosition = function () {
  7253. this.computeWorldMatrix();
  7254. return this._absolutePosition;
  7255. };
  7256. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7257. if (!absolutePosition) {
  7258. return;
  7259. }
  7260. var absolutePositionX;
  7261. var absolutePositionY;
  7262. var absolutePositionZ;
  7263. if (absolutePosition.x === undefined) {
  7264. if (arguments.length < 3) {
  7265. return;
  7266. }
  7267. absolutePositionX = arguments[0];
  7268. absolutePositionY = arguments[1];
  7269. absolutePositionZ = arguments[2];
  7270. } else {
  7271. absolutePositionX = absolutePosition.x;
  7272. absolutePositionY = absolutePosition.y;
  7273. absolutePositionZ = absolutePosition.z;
  7274. }
  7275. if (this.parent) {
  7276. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7277. invertParentWorldMatrix.invert();
  7278. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7279. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7280. } else {
  7281. this.position.x = absolutePositionX;
  7282. this.position.y = absolutePositionY;
  7283. this.position.z = absolutePositionZ;
  7284. }
  7285. };
  7286. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7287. this._pivotMatrix = matrix;
  7288. this._cache.pivotMatrixUpdated = true;
  7289. };
  7290. AbstractMesh.prototype.getPivotMatrix = function () {
  7291. return this._pivotMatrix;
  7292. };
  7293. AbstractMesh.prototype._isSynchronized = function () {
  7294. if (this._isDirty) {
  7295. return false;
  7296. }
  7297. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7298. return false;
  7299. if (this._cache.pivotMatrixUpdated) {
  7300. return false;
  7301. }
  7302. if (this.infiniteDistance) {
  7303. return false;
  7304. }
  7305. if (!this._cache.position.equals(this.position))
  7306. return false;
  7307. if (this.rotationQuaternion) {
  7308. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7309. return false;
  7310. } else {
  7311. if (!this._cache.rotation.equals(this.rotation))
  7312. return false;
  7313. }
  7314. if (!this._cache.scaling.equals(this.scaling))
  7315. return false;
  7316. return true;
  7317. };
  7318. AbstractMesh.prototype._initCache = function () {
  7319. _super.prototype._initCache.call(this);
  7320. this._cache.localMatrixUpdated = false;
  7321. this._cache.position = BABYLON.Vector3.Zero();
  7322. this._cache.scaling = BABYLON.Vector3.Zero();
  7323. this._cache.rotation = BABYLON.Vector3.Zero();
  7324. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7325. };
  7326. AbstractMesh.prototype.markAsDirty = function (property) {
  7327. if (property === "rotation") {
  7328. this.rotationQuaternion = null;
  7329. }
  7330. this._currentRenderId = Number.MAX_VALUE;
  7331. this._isDirty = true;
  7332. };
  7333. AbstractMesh.prototype._updateBoundingInfo = function () {
  7334. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7335. this._boundingInfo._update(this.worldMatrixFromCache);
  7336. if (!this.subMeshes) {
  7337. return;
  7338. }
  7339. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7340. var subMesh = this.subMeshes[subIndex];
  7341. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7342. }
  7343. };
  7344. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7345. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7346. return this._worldMatrix;
  7347. }
  7348. this._cache.position.copyFrom(this.position);
  7349. this._cache.scaling.copyFrom(this.scaling);
  7350. this._cache.pivotMatrixUpdated = false;
  7351. this._currentRenderId = this.getScene().getRenderId();
  7352. this._isDirty = false;
  7353. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7354. if (this.rotationQuaternion) {
  7355. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7356. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7357. } else {
  7358. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7359. this._cache.rotation.copyFrom(this.rotation);
  7360. }
  7361. if (this.infiniteDistance && !this.parent) {
  7362. var camera = this.getScene().activeCamera;
  7363. var cameraWorldMatrix = camera.getWorldMatrix();
  7364. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7365. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7366. } else {
  7367. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7368. }
  7369. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7370. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7371. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7372. var localPosition = this.position.clone();
  7373. var zero = this.getScene().activeCamera.position.clone();
  7374. if (this.parent && this.parent.position) {
  7375. localPosition.addInPlace(this.parent.position);
  7376. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7377. }
  7378. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7379. zero = this.getScene().activeCamera.position;
  7380. } else {
  7381. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7382. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7383. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7384. zero.y = localPosition.y + 0.001;
  7385. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7386. zero.z = localPosition.z + 0.001;
  7387. }
  7388. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7389. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7390. this._localBillboard.invert();
  7391. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7392. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7393. }
  7394. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7395. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7396. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7397. } else {
  7398. this._worldMatrix.copyFrom(this._localWorld);
  7399. }
  7400. this._updateBoundingInfo();
  7401. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7402. return this._worldMatrix;
  7403. };
  7404. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7405. this.computeWorldMatrix();
  7406. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7407. };
  7408. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7409. this.computeWorldMatrix();
  7410. var invLocalWorldMatrix = this._localWorld.clone();
  7411. invLocalWorldMatrix.invert();
  7412. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7413. };
  7414. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7415. this.computeWorldMatrix();
  7416. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7417. };
  7418. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7419. yawCor = yawCor || 0;
  7420. pitchCor = pitchCor || 0;
  7421. rollCor = rollCor || 0;
  7422. var dv = targetPoint.subtract(this.position);
  7423. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7424. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7425. var pitch = Math.atan2(dv.y, len);
  7426. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7427. };
  7428. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7429. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7430. return false;
  7431. }
  7432. return true;
  7433. };
  7434. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7435. if (!this._boundingInfo || !mesh._boundingInfo) {
  7436. return false;
  7437. }
  7438. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7439. };
  7440. AbstractMesh.prototype.intersectsPoint = function (point) {
  7441. if (!this._boundingInfo) {
  7442. return false;
  7443. }
  7444. return this._boundingInfo.intersectsPoint(point);
  7445. };
  7446. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7447. var physicsEngine = this.getScene().getPhysicsEngine();
  7448. if (!physicsEngine) {
  7449. return;
  7450. }
  7451. if (impostor.impostor) {
  7452. options = impostor;
  7453. impostor = impostor.impostor;
  7454. }
  7455. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7456. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7457. physicsEngine._unregisterMesh(this);
  7458. return;
  7459. }
  7460. options.mass = options.mass || 0;
  7461. options.friction = options.friction || 0.2;
  7462. options.restitution = options.restitution || 0.9;
  7463. this._physicImpostor = impostor;
  7464. this._physicsMass = options.mass;
  7465. this._physicsFriction = options.friction;
  7466. this._physicRestitution = options.restitution;
  7467. physicsEngine._registerMesh(this, impostor, options);
  7468. };
  7469. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7470. if (!this._physicImpostor) {
  7471. return BABYLON.PhysicsEngine.NoImpostor;
  7472. }
  7473. return this._physicImpostor;
  7474. };
  7475. AbstractMesh.prototype.getPhysicsMass = function () {
  7476. if (!this._physicsMass) {
  7477. return 0;
  7478. }
  7479. return this._physicsMass;
  7480. };
  7481. AbstractMesh.prototype.getPhysicsFriction = function () {
  7482. if (!this._physicsFriction) {
  7483. return 0;
  7484. }
  7485. return this._physicsFriction;
  7486. };
  7487. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7488. if (!this._physicRestitution) {
  7489. return 0;
  7490. }
  7491. return this._physicRestitution;
  7492. };
  7493. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7494. if (!this._physicImpostor) {
  7495. return;
  7496. }
  7497. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7498. };
  7499. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7500. if (!this._physicImpostor) {
  7501. return;
  7502. }
  7503. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7504. };
  7505. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7506. if (!this._physicImpostor) {
  7507. return;
  7508. }
  7509. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7510. };
  7511. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7512. var globalPosition = this.getAbsolutePosition();
  7513. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7514. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7515. this._collider.radius = this.ellipsoid;
  7516. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7517. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7518. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7519. this.position.addInPlace(this._diffPositionForCollisions);
  7520. }
  7521. };
  7522. /**
  7523. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7524. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7525. */
  7526. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7527. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7528. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7529. if (!this._submeshesOctree) {
  7530. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7531. }
  7532. this.computeWorldMatrix(true);
  7533. var bbox = this.getBoundingInfo().boundingBox;
  7534. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7535. return this._submeshesOctree;
  7536. };
  7537. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7538. this._generatePointsArray();
  7539. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7540. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7541. subMesh._lastColliderWorldVertices = [];
  7542. subMesh._trianglePlanes = [];
  7543. var start = subMesh.verticesStart;
  7544. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7545. for (var i = start; i < end; i++) {
  7546. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7547. }
  7548. }
  7549. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7550. };
  7551. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7552. var subMeshes;
  7553. var len;
  7554. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7555. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7556. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7557. len = intersections.length;
  7558. subMeshes = intersections.data;
  7559. } else {
  7560. subMeshes = this.subMeshes;
  7561. len = subMeshes.length;
  7562. }
  7563. for (var index = 0; index < len; index++) {
  7564. var subMesh = subMeshes[index];
  7565. if (len > 1 && !subMesh._checkCollision(collider))
  7566. continue;
  7567. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7568. }
  7569. };
  7570. AbstractMesh.prototype._checkCollision = function (collider) {
  7571. if (!this._boundingInfo._checkCollision(collider))
  7572. return;
  7573. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7574. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7575. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7576. };
  7577. AbstractMesh.prototype._generatePointsArray = function () {
  7578. return false;
  7579. };
  7580. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7581. var pickingInfo = new BABYLON.PickingInfo();
  7582. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7583. return pickingInfo;
  7584. }
  7585. if (!this._generatePointsArray()) {
  7586. return pickingInfo;
  7587. }
  7588. var intersectInfo = null;
  7589. var subMeshes;
  7590. var len;
  7591. if (this._submeshesOctree && this.useOctreeForPicking) {
  7592. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7593. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7594. len = intersections.length;
  7595. subMeshes = intersections.data;
  7596. } else {
  7597. subMeshes = this.subMeshes;
  7598. len = subMeshes.length;
  7599. }
  7600. for (var index = 0; index < len; index++) {
  7601. var subMesh = subMeshes[index];
  7602. if (len > 1 && !subMesh.canIntersects(ray))
  7603. continue;
  7604. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7605. if (currentIntersectInfo) {
  7606. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7607. intersectInfo = currentIntersectInfo;
  7608. if (fastCheck) {
  7609. break;
  7610. }
  7611. }
  7612. }
  7613. }
  7614. if (intersectInfo) {
  7615. var world = this.getWorldMatrix();
  7616. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7617. var direction = ray.direction.clone();
  7618. direction.normalize();
  7619. direction = direction.scale(intersectInfo.distance);
  7620. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7621. var pickedPoint = worldOrigin.add(worldDirection);
  7622. pickingInfo.hit = true;
  7623. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7624. pickingInfo.pickedPoint = pickedPoint;
  7625. pickingInfo.pickedMesh = this;
  7626. pickingInfo.bu = intersectInfo.bu;
  7627. pickingInfo.bv = intersectInfo.bv;
  7628. pickingInfo.faceId = intersectInfo.faceId;
  7629. return pickingInfo;
  7630. }
  7631. return pickingInfo;
  7632. };
  7633. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7634. return null;
  7635. };
  7636. AbstractMesh.prototype.releaseSubMeshes = function () {
  7637. if (this.subMeshes) {
  7638. while (this.subMeshes.length) {
  7639. this.subMeshes[0].dispose();
  7640. }
  7641. } else {
  7642. this.subMeshes = new Array();
  7643. }
  7644. };
  7645. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7646. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7647. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7648. }
  7649. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7650. var other = this._intersectionsInProgress[index];
  7651. var pos = other._intersectionsInProgress.indexOf(this);
  7652. other._intersectionsInProgress.splice(pos, 1);
  7653. }
  7654. this._intersectionsInProgress = [];
  7655. this.releaseSubMeshes();
  7656. var index = this.getScene().meshes.indexOf(this);
  7657. if (index != -1) {
  7658. this.getScene().meshes.splice(index, 1);
  7659. }
  7660. if (!doNotRecurse) {
  7661. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7662. if (this.getScene().particleSystems[index].emitter == this) {
  7663. this.getScene().particleSystems[index].dispose();
  7664. index--;
  7665. }
  7666. }
  7667. var objects = this.getScene().meshes.slice(0);
  7668. for (index = 0; index < objects.length; index++) {
  7669. if (objects[index].parent == this) {
  7670. objects[index].dispose();
  7671. }
  7672. }
  7673. } else {
  7674. for (index = 0; index < this.getScene().meshes.length; index++) {
  7675. var obj = this.getScene().meshes[index];
  7676. if (obj.parent === this) {
  7677. obj.parent = null;
  7678. obj.computeWorldMatrix(true);
  7679. }
  7680. }
  7681. }
  7682. this._isDisposed = true;
  7683. if (this.onDispose) {
  7684. this.onDispose();
  7685. }
  7686. };
  7687. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7688. AbstractMesh._BILLBOARDMODE_X = 1;
  7689. AbstractMesh._BILLBOARDMODE_Y = 2;
  7690. AbstractMesh._BILLBOARDMODE_Z = 4;
  7691. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7692. return AbstractMesh;
  7693. })(BABYLON.Node);
  7694. BABYLON.AbstractMesh = AbstractMesh;
  7695. })(BABYLON || (BABYLON = {}));
  7696. var __extends = this.__extends || function (d, b) {
  7697. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7698. function __() { this.constructor = d; }
  7699. __.prototype = b.prototype;
  7700. d.prototype = new __();
  7701. };
  7702. var BABYLON;
  7703. (function (BABYLON) {
  7704. var _InstancesBatch = (function () {
  7705. function _InstancesBatch() {
  7706. this.mustReturn = false;
  7707. this.visibleInstances = new Array();
  7708. this.renderSelf = new Array();
  7709. }
  7710. return _InstancesBatch;
  7711. })();
  7712. BABYLON._InstancesBatch = _InstancesBatch;
  7713. var Mesh = (function (_super) {
  7714. __extends(Mesh, _super);
  7715. function Mesh(name, scene) {
  7716. _super.call(this, name, scene);
  7717. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7718. this.instances = new Array();
  7719. this._onBeforeRenderCallbacks = new Array();
  7720. this._onAfterRenderCallbacks = new Array();
  7721. this._visibleInstances = {};
  7722. this._renderIdForInstances = new Array();
  7723. this._batchCache = new _InstancesBatch();
  7724. this._instancesBufferSize = 32 * 16 * 4;
  7725. }
  7726. Mesh.prototype.getTotalVertices = function () {
  7727. if (!this._geometry) {
  7728. return 0;
  7729. }
  7730. return this._geometry.getTotalVertices();
  7731. };
  7732. Mesh.prototype.getVerticesData = function (kind) {
  7733. if (!this._geometry) {
  7734. return null;
  7735. }
  7736. return this._geometry.getVerticesData(kind);
  7737. };
  7738. Mesh.prototype.getVertexBuffer = function (kind) {
  7739. if (!this._geometry) {
  7740. return undefined;
  7741. }
  7742. return this._geometry.getVertexBuffer(kind);
  7743. };
  7744. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7745. if (!this._geometry) {
  7746. if (this._delayInfo) {
  7747. return this._delayInfo.indexOf(kind) !== -1;
  7748. }
  7749. return false;
  7750. }
  7751. return this._geometry.isVerticesDataPresent(kind);
  7752. };
  7753. Mesh.prototype.getVerticesDataKinds = function () {
  7754. if (!this._geometry) {
  7755. var result = [];
  7756. if (this._delayInfo) {
  7757. for (var kind in this._delayInfo) {
  7758. result.push(kind);
  7759. }
  7760. }
  7761. return result;
  7762. }
  7763. return this._geometry.getVerticesDataKinds();
  7764. };
  7765. Mesh.prototype.getTotalIndices = function () {
  7766. if (!this._geometry) {
  7767. return 0;
  7768. }
  7769. return this._geometry.getTotalIndices();
  7770. };
  7771. Mesh.prototype.getIndices = function () {
  7772. if (!this._geometry) {
  7773. return [];
  7774. }
  7775. return this._geometry.getIndices();
  7776. };
  7777. Mesh.prototype.isReady = function () {
  7778. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7779. return false;
  7780. }
  7781. return _super.prototype.isReady.call(this);
  7782. };
  7783. Mesh.prototype.isDisposed = function () {
  7784. return this._isDisposed;
  7785. };
  7786. Mesh.prototype._preActivate = function () {
  7787. var sceneRenderId = this.getScene().getRenderId();
  7788. if (this._preActivateId == sceneRenderId) {
  7789. return;
  7790. }
  7791. this._preActivateId = sceneRenderId;
  7792. this._visibleInstances = null;
  7793. };
  7794. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7795. if (!this._visibleInstances) {
  7796. this._visibleInstances = {};
  7797. this._visibleInstances.defaultRenderId = renderId;
  7798. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7799. }
  7800. if (!this._visibleInstances[renderId]) {
  7801. this._visibleInstances[renderId] = new Array();
  7802. }
  7803. this._visibleInstances[renderId].push(instance);
  7804. };
  7805. Mesh.prototype.refreshBoundingInfo = function () {
  7806. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7807. if (data) {
  7808. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7809. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7810. }
  7811. if (this.subMeshes) {
  7812. for (var index = 0; index < this.subMeshes.length; index++) {
  7813. this.subMeshes[index].refreshBoundingInfo();
  7814. }
  7815. }
  7816. this._updateBoundingInfo();
  7817. };
  7818. Mesh.prototype._createGlobalSubMesh = function () {
  7819. var totalVertices = this.getTotalVertices();
  7820. if (!totalVertices || !this.getIndices()) {
  7821. return null;
  7822. }
  7823. this.releaseSubMeshes();
  7824. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7825. };
  7826. Mesh.prototype.subdivide = function (count) {
  7827. if (count < 1) {
  7828. return;
  7829. }
  7830. var totalIndices = this.getTotalIndices();
  7831. var subdivisionSize = (totalIndices / count) | 0;
  7832. var offset = 0;
  7833. while (subdivisionSize % 3 != 0) {
  7834. subdivisionSize++;
  7835. }
  7836. this.releaseSubMeshes();
  7837. for (var index = 0; index < count; index++) {
  7838. if (offset >= totalIndices) {
  7839. break;
  7840. }
  7841. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7842. offset += subdivisionSize;
  7843. }
  7844. this.synchronizeInstances();
  7845. };
  7846. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7847. if (kind instanceof Array) {
  7848. var temp = data;
  7849. data = kind;
  7850. kind = temp;
  7851. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7852. }
  7853. if (!this._geometry) {
  7854. var vertexData = new BABYLON.VertexData();
  7855. vertexData.set(data, kind);
  7856. var scene = this.getScene();
  7857. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7858. } else {
  7859. this._geometry.setVerticesData(kind, data, updatable);
  7860. }
  7861. };
  7862. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7863. if (!this._geometry) {
  7864. return;
  7865. }
  7866. if (!makeItUnique) {
  7867. this._geometry.updateVerticesData(kind, data, updateExtends);
  7868. } else {
  7869. this.makeGeometryUnique();
  7870. this.updateVerticesData(kind, data, updateExtends, false);
  7871. }
  7872. };
  7873. Mesh.prototype.makeGeometryUnique = function () {
  7874. if (!this._geometry) {
  7875. return;
  7876. }
  7877. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7878. geometry.applyToMesh(this);
  7879. };
  7880. Mesh.prototype.setIndices = function (indices) {
  7881. if (!this._geometry) {
  7882. var vertexData = new BABYLON.VertexData();
  7883. vertexData.indices = indices;
  7884. var scene = this.getScene();
  7885. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7886. } else {
  7887. this._geometry.setIndices(indices);
  7888. }
  7889. };
  7890. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7891. var engine = this.getScene().getEngine();
  7892. var indexToBind = this._geometry.getIndexBuffer();
  7893. if (wireframe) {
  7894. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7895. }
  7896. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7897. };
  7898. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7899. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7900. return;
  7901. }
  7902. var engine = this.getScene().getEngine();
  7903. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7904. };
  7905. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7906. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7907. return;
  7908. }
  7909. var engine = this.getScene().getEngine();
  7910. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7911. };
  7912. Mesh.prototype.registerBeforeRender = function (func) {
  7913. this._onBeforeRenderCallbacks.push(func);
  7914. };
  7915. Mesh.prototype.unregisterBeforeRender = function (func) {
  7916. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7917. if (index > -1) {
  7918. this._onBeforeRenderCallbacks.splice(index, 1);
  7919. }
  7920. };
  7921. Mesh.prototype.registerAfterRender = function (func) {
  7922. this._onAfterRenderCallbacks.push(func);
  7923. };
  7924. Mesh.prototype.unregisterAfterRender = function (func) {
  7925. var index = this._onAfterRenderCallbacks.indexOf(func);
  7926. if (index > -1) {
  7927. this._onAfterRenderCallbacks.splice(index, 1);
  7928. }
  7929. };
  7930. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7931. var scene = this.getScene();
  7932. this._batchCache.mustReturn = false;
  7933. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7934. this._batchCache.visibleInstances[subMeshId] = null;
  7935. if (this._visibleInstances) {
  7936. var currentRenderId = scene.getRenderId();
  7937. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7938. var selfRenderId = this._renderId;
  7939. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7941. currentRenderId = this._visibleInstances.defaultRenderId;
  7942. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7943. }
  7944. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7945. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7946. this._batchCache.mustReturn = true;
  7947. return this._batchCache;
  7948. }
  7949. if (currentRenderId !== selfRenderId) {
  7950. this._batchCache.renderSelf[subMeshId] = false;
  7951. }
  7952. }
  7953. this._renderIdForInstances[subMeshId] = currentRenderId;
  7954. }
  7955. return this._batchCache;
  7956. };
  7957. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7958. var matricesCount = this.instances.length + 1;
  7959. var bufferSize = matricesCount * 16 * 4;
  7960. while (this._instancesBufferSize < bufferSize) {
  7961. this._instancesBufferSize *= 2;
  7962. }
  7963. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7964. if (this._worldMatricesInstancesBuffer) {
  7965. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7966. }
  7967. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7968. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7969. }
  7970. var offset = 0;
  7971. var instancesCount = 0;
  7972. var world = this.getWorldMatrix();
  7973. if (batch.renderSelf[subMesh._id]) {
  7974. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7975. offset += 16;
  7976. instancesCount++;
  7977. }
  7978. var visibleInstances = batch.visibleInstances[subMesh._id];
  7979. if (visibleInstances) {
  7980. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7981. var instance = visibleInstances[instanceIndex];
  7982. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7983. offset += 16;
  7984. instancesCount++;
  7985. }
  7986. }
  7987. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7988. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7989. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7990. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  7991. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  7992. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  7993. this._draw(subMesh, !wireFrame, instancesCount);
  7994. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  7995. };
  7996. Mesh.prototype.render = function (subMesh) {
  7997. var scene = this.getScene();
  7998. var batch = this._getInstancesRenderList(subMesh._id);
  7999. if (batch.mustReturn) {
  8000. return;
  8001. }
  8002. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8003. return;
  8004. }
  8005. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8006. this._onBeforeRenderCallbacks[callbackIndex]();
  8007. }
  8008. var engine = scene.getEngine();
  8009. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8010. var effectiveMaterial = subMesh.getMaterial();
  8011. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8012. return;
  8013. }
  8014. var savedDepthWrite = engine.getDepthWrite();
  8015. if (this.renderOutline) {
  8016. engine.setDepthWrite(false);
  8017. scene.getOutlineRenderer().render(subMesh, batch);
  8018. }
  8019. effectiveMaterial._preBind();
  8020. var effect = effectiveMaterial.getEffect();
  8021. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8022. this._bind(subMesh, effect, wireFrame);
  8023. var world = this.getWorldMatrix();
  8024. effectiveMaterial.bind(world, this);
  8025. if (hardwareInstancedRendering) {
  8026. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8027. } else {
  8028. if (batch.renderSelf[subMesh._id]) {
  8029. this._draw(subMesh, !wireFrame);
  8030. }
  8031. if (batch.visibleInstances[subMesh._id]) {
  8032. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8033. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8034. world = instance.getWorldMatrix();
  8035. effectiveMaterial.bindOnlyWorldMatrix(world);
  8036. this._draw(subMesh, !wireFrame);
  8037. }
  8038. }
  8039. }
  8040. effectiveMaterial.unbind();
  8041. if (this.renderOutline && savedDepthWrite) {
  8042. engine.setDepthWrite(true);
  8043. engine.setColorWrite(false);
  8044. scene.getOutlineRenderer().render(subMesh, batch);
  8045. engine.setColorWrite(true);
  8046. }
  8047. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8048. this._onAfterRenderCallbacks[callbackIndex]();
  8049. }
  8050. };
  8051. Mesh.prototype.getEmittedParticleSystems = function () {
  8052. var results = new Array();
  8053. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8054. var particleSystem = this.getScene().particleSystems[index];
  8055. if (particleSystem.emitter === this) {
  8056. results.push(particleSystem);
  8057. }
  8058. }
  8059. return results;
  8060. };
  8061. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8062. var results = new Array();
  8063. var descendants = this.getDescendants();
  8064. descendants.push(this);
  8065. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8066. var particleSystem = this.getScene().particleSystems[index];
  8067. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8068. results.push(particleSystem);
  8069. }
  8070. }
  8071. return results;
  8072. };
  8073. Mesh.prototype.getChildren = function () {
  8074. var results = [];
  8075. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8076. var mesh = this.getScene().meshes[index];
  8077. if (mesh.parent == this) {
  8078. results.push(mesh);
  8079. }
  8080. }
  8081. return results;
  8082. };
  8083. Mesh.prototype._checkDelayState = function () {
  8084. var _this = this;
  8085. var that = this;
  8086. var scene = this.getScene();
  8087. if (this._geometry) {
  8088. this._geometry.load(scene);
  8089. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8090. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8091. scene._addPendingData(that);
  8092. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8093. _this._delayLoadingFunction(JSON.parse(data), _this);
  8094. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8095. scene._removePendingData(_this);
  8096. }, function () {
  8097. }, scene.database);
  8098. }
  8099. };
  8100. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8102. return false;
  8103. }
  8104. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8105. return false;
  8106. }
  8107. this._checkDelayState();
  8108. return true;
  8109. };
  8110. Mesh.prototype.setMaterialByID = function (id) {
  8111. var materials = this.getScene().materials;
  8112. for (var index = 0; index < materials.length; index++) {
  8113. if (materials[index].id == id) {
  8114. this.material = materials[index];
  8115. return;
  8116. }
  8117. }
  8118. var multiMaterials = this.getScene().multiMaterials;
  8119. for (index = 0; index < multiMaterials.length; index++) {
  8120. if (multiMaterials[index].id == id) {
  8121. this.material = multiMaterials[index];
  8122. return;
  8123. }
  8124. }
  8125. };
  8126. Mesh.prototype.getAnimatables = function () {
  8127. var results = [];
  8128. if (this.material) {
  8129. results.push(this.material);
  8130. }
  8131. return results;
  8132. };
  8133. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8134. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8135. return;
  8136. }
  8137. this._resetPointsArrayCache();
  8138. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8139. var temp = [];
  8140. for (var index = 0; index < data.length; index += 3) {
  8141. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8142. }
  8143. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8145. return;
  8146. }
  8147. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8148. for (index = 0; index < data.length; index += 3) {
  8149. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8150. }
  8151. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8152. };
  8153. Mesh.prototype._resetPointsArrayCache = function () {
  8154. this._positions = null;
  8155. };
  8156. Mesh.prototype._generatePointsArray = function () {
  8157. if (this._positions)
  8158. return true;
  8159. this._positions = [];
  8160. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8161. if (!data) {
  8162. return false;
  8163. }
  8164. for (var index = 0; index < data.length; index += 3) {
  8165. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8166. }
  8167. return true;
  8168. };
  8169. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8170. var result = new BABYLON.Mesh(name, this.getScene());
  8171. this._geometry.applyToMesh(result);
  8172. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8173. result.material = this.material;
  8174. if (newParent) {
  8175. result.parent = newParent;
  8176. }
  8177. if (!doNotCloneChildren) {
  8178. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8179. var mesh = this.getScene().meshes[index];
  8180. if (mesh.parent == this) {
  8181. mesh.clone(mesh.name, result);
  8182. }
  8183. }
  8184. }
  8185. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8186. var system = this.getScene().particleSystems[index];
  8187. if (system.emitter == this) {
  8188. system.clone(system.name, result);
  8189. }
  8190. }
  8191. result.computeWorldMatrix(true);
  8192. return result;
  8193. };
  8194. Mesh.prototype.dispose = function (doNotRecurse) {
  8195. if (this._geometry) {
  8196. this._geometry.releaseForMesh(this, true);
  8197. }
  8198. if (this._worldMatricesInstancesBuffer) {
  8199. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8200. this._worldMatricesInstancesBuffer = null;
  8201. }
  8202. while (this.instances.length) {
  8203. this.instances[0].dispose();
  8204. }
  8205. _super.prototype.dispose.call(this, doNotRecurse);
  8206. };
  8207. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8208. var _this = this;
  8209. var scene = this.getScene();
  8210. var onload = function (img) {
  8211. var canvas = document.createElement("canvas");
  8212. var context = canvas.getContext("2d");
  8213. var heightMapWidth = img.width;
  8214. var heightMapHeight = img.height;
  8215. canvas.width = heightMapWidth;
  8216. canvas.height = heightMapHeight;
  8217. context.drawImage(img, 0, 0);
  8218. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8219. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8220. };
  8221. BABYLON.Tools.LoadImage(url, onload, function () {
  8222. }, scene.database);
  8223. };
  8224. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8225. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8226. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8227. return;
  8228. }
  8229. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8230. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8231. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8232. var position = BABYLON.Vector3.Zero();
  8233. var normal = BABYLON.Vector3.Zero();
  8234. var uv = BABYLON.Vector2.Zero();
  8235. for (var index = 0; index < positions.length; index += 3) {
  8236. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8237. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8238. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8239. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8240. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8241. var pos = (u + v * heightMapWidth) * 4;
  8242. var r = buffer[pos] / 255.0;
  8243. var g = buffer[pos + 1] / 255.0;
  8244. var b = buffer[pos + 2] / 255.0;
  8245. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8246. normal.normalize();
  8247. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8248. position = position.add(normal);
  8249. position.toArray(positions, index);
  8250. }
  8251. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8252. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8253. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8254. };
  8255. Mesh.prototype.convertToFlatShadedMesh = function () {
  8256. var kinds = this.getVerticesDataKinds();
  8257. var vbs = [];
  8258. var data = [];
  8259. var newdata = [];
  8260. var updatableNormals = false;
  8261. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8262. var kind = kinds[kindIndex];
  8263. var vertexBuffer = this.getVertexBuffer(kind);
  8264. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8265. updatableNormals = vertexBuffer.isUpdatable();
  8266. kinds.splice(kindIndex, 1);
  8267. kindIndex--;
  8268. continue;
  8269. }
  8270. vbs[kind] = vertexBuffer;
  8271. data[kind] = vbs[kind].getData();
  8272. newdata[kind] = [];
  8273. }
  8274. var previousSubmeshes = this.subMeshes.slice(0);
  8275. var indices = this.getIndices();
  8276. var totalIndices = this.getTotalIndices();
  8277. for (index = 0; index < totalIndices; index++) {
  8278. var vertexIndex = indices[index];
  8279. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8280. kind = kinds[kindIndex];
  8281. var stride = vbs[kind].getStrideSize();
  8282. for (var offset = 0; offset < stride; offset++) {
  8283. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8284. }
  8285. }
  8286. }
  8287. var normals = [];
  8288. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8289. for (var index = 0; index < totalIndices; index += 3) {
  8290. indices[index] = index;
  8291. indices[index + 1] = index + 1;
  8292. indices[index + 2] = index + 2;
  8293. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8294. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8295. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8296. var p1p2 = p1.subtract(p2);
  8297. var p3p2 = p3.subtract(p2);
  8298. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8299. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8300. normals.push(normal.x);
  8301. normals.push(normal.y);
  8302. normals.push(normal.z);
  8303. }
  8304. }
  8305. this.setIndices(indices);
  8306. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8307. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8308. kind = kinds[kindIndex];
  8309. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8310. }
  8311. this.releaseSubMeshes();
  8312. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8313. var previousOne = previousSubmeshes[submeshIndex];
  8314. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8315. }
  8316. this.synchronizeInstances();
  8317. };
  8318. Mesh.prototype.createInstance = function (name) {
  8319. return new BABYLON.InstancedMesh(name, this);
  8320. };
  8321. Mesh.prototype.synchronizeInstances = function () {
  8322. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8323. var instance = this.instances[instanceIndex];
  8324. instance._syncSubMeshes();
  8325. }
  8326. };
  8327. Mesh.CreateBox = function (name, size, scene, updatable) {
  8328. var box = new BABYLON.Mesh(name, scene);
  8329. var vertexData = BABYLON.VertexData.CreateBox(size);
  8330. vertexData.applyToMesh(box, updatable);
  8331. return box;
  8332. };
  8333. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8334. var sphere = new BABYLON.Mesh(name, scene);
  8335. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8336. vertexData.applyToMesh(sphere, updatable);
  8337. return sphere;
  8338. };
  8339. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8340. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8341. if (scene !== undefined) {
  8342. updatable = scene;
  8343. }
  8344. scene = subdivisions;
  8345. subdivisions = 1;
  8346. }
  8347. var cylinder = new BABYLON.Mesh(name, scene);
  8348. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8349. vertexData.applyToMesh(cylinder, updatable);
  8350. return cylinder;
  8351. };
  8352. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8353. var torus = new BABYLON.Mesh(name, scene);
  8354. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8355. vertexData.applyToMesh(torus, updatable);
  8356. return torus;
  8357. };
  8358. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8359. var torusKnot = new BABYLON.Mesh(name, scene);
  8360. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8361. vertexData.applyToMesh(torusKnot, updatable);
  8362. return torusKnot;
  8363. };
  8364. Mesh.CreateLines = function (name, points, scene, updatable) {
  8365. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8366. var vertexData = BABYLON.VertexData.CreateLines(points);
  8367. vertexData.applyToMesh(lines, updatable);
  8368. return lines;
  8369. };
  8370. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8371. var plane = new BABYLON.Mesh(name, scene);
  8372. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8373. vertexData.applyToMesh(plane, updatable);
  8374. return plane;
  8375. };
  8376. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8377. var ground = new BABYLON.GroundMesh(name, scene);
  8378. ground._setReady(false);
  8379. ground._subdivisions = subdivisions;
  8380. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8381. vertexData.applyToMesh(ground, updatable);
  8382. ground._setReady(true);
  8383. return ground;
  8384. };
  8385. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8386. var tiledGround = new BABYLON.Mesh(name, scene);
  8387. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8388. vertexData.applyToMesh(tiledGround, updatable);
  8389. return tiledGround;
  8390. };
  8391. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8392. var ground = new BABYLON.GroundMesh(name, scene);
  8393. ground._subdivisions = subdivisions;
  8394. ground._setReady(false);
  8395. var onload = function (img) {
  8396. var canvas = document.createElement("canvas");
  8397. var context = canvas.getContext("2d");
  8398. var heightMapWidth = img.width;
  8399. var heightMapHeight = img.height;
  8400. canvas.width = heightMapWidth;
  8401. canvas.height = heightMapHeight;
  8402. context.drawImage(img, 0, 0);
  8403. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8404. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8405. vertexData.applyToMesh(ground, updatable);
  8406. ground._setReady(true);
  8407. };
  8408. BABYLON.Tools.LoadImage(url, onload, function () {
  8409. }, scene.database);
  8410. return ground;
  8411. };
  8412. Mesh.MinMax = function (meshes) {
  8413. var minVector = null;
  8414. var maxVector = null;
  8415. for (var i in meshes) {
  8416. var mesh = meshes[i];
  8417. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8418. if (!minVector) {
  8419. minVector = boundingBox.minimumWorld;
  8420. maxVector = boundingBox.maximumWorld;
  8421. continue;
  8422. }
  8423. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8424. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8425. }
  8426. return {
  8427. min: minVector,
  8428. max: maxVector
  8429. };
  8430. };
  8431. Mesh.Center = function (meshesOrMinMaxVector) {
  8432. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8433. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8434. };
  8435. return Mesh;
  8436. })(BABYLON.AbstractMesh);
  8437. BABYLON.Mesh = Mesh;
  8438. })(BABYLON || (BABYLON = {}));
  8439. var __extends = this.__extends || function (d, b) {
  8440. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8441. function __() { this.constructor = d; }
  8442. __.prototype = b.prototype;
  8443. d.prototype = new __();
  8444. };
  8445. var BABYLON;
  8446. (function (BABYLON) {
  8447. var GroundMesh = (function (_super) {
  8448. __extends(GroundMesh, _super);
  8449. function GroundMesh(name, scene) {
  8450. _super.call(this, name, scene);
  8451. this.generateOctree = false;
  8452. this._worldInverse = new BABYLON.Matrix();
  8453. }
  8454. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8455. get: function () {
  8456. return this._subdivisions;
  8457. },
  8458. enumerable: true,
  8459. configurable: true
  8460. });
  8461. GroundMesh.prototype.optimize = function (chunksCount) {
  8462. this.subdivide(this._subdivisions);
  8463. this.createOrUpdateSubmeshesOctree(32);
  8464. };
  8465. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8466. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8467. this.getWorldMatrix().invertToRef(this._worldInverse);
  8468. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8469. var pickInfo = this.intersects(ray);
  8470. if (pickInfo.hit) {
  8471. return pickInfo.pickedPoint.y;
  8472. }
  8473. return 0;
  8474. };
  8475. return GroundMesh;
  8476. })(BABYLON.Mesh);
  8477. BABYLON.GroundMesh = GroundMesh;
  8478. })(BABYLON || (BABYLON = {}));
  8479. var __extends = this.__extends || function (d, b) {
  8480. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8481. function __() { this.constructor = d; }
  8482. __.prototype = b.prototype;
  8483. d.prototype = new __();
  8484. };
  8485. var BABYLON;
  8486. (function (BABYLON) {
  8487. var InstancedMesh = (function (_super) {
  8488. __extends(InstancedMesh, _super);
  8489. function InstancedMesh(name, source) {
  8490. _super.call(this, name, source.getScene());
  8491. source.instances.push(this);
  8492. this._sourceMesh = source;
  8493. this.position.copyFrom(source.position);
  8494. this.rotation.copyFrom(source.rotation);
  8495. this.scaling.copyFrom(source.scaling);
  8496. if (source.rotationQuaternion) {
  8497. this.rotationQuaternion = source.rotationQuaternion.clone();
  8498. }
  8499. this.infiniteDistance = source.infiniteDistance;
  8500. this.setPivotMatrix(source.getPivotMatrix());
  8501. this.refreshBoundingInfo();
  8502. this._syncSubMeshes();
  8503. }
  8504. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8505. get: function () {
  8506. return this._sourceMesh.receiveShadows;
  8507. },
  8508. enumerable: true,
  8509. configurable: true
  8510. });
  8511. Object.defineProperty(InstancedMesh.prototype, "material", {
  8512. get: function () {
  8513. return this._sourceMesh.material;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8519. get: function () {
  8520. return this._sourceMesh.visibility;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8526. get: function () {
  8527. return this._sourceMesh.skeleton;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. InstancedMesh.prototype.getTotalVertices = function () {
  8533. return this._sourceMesh.getTotalVertices();
  8534. };
  8535. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8536. get: function () {
  8537. return this._sourceMesh;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. InstancedMesh.prototype.getVerticesData = function (kind) {
  8543. return this._sourceMesh.getVerticesData(kind);
  8544. };
  8545. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8546. return this._sourceMesh.isVerticesDataPresent(kind);
  8547. };
  8548. InstancedMesh.prototype.getIndices = function () {
  8549. return this._sourceMesh.getIndices();
  8550. };
  8551. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8552. get: function () {
  8553. return this._sourceMesh._positions;
  8554. },
  8555. enumerable: true,
  8556. configurable: true
  8557. });
  8558. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8559. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8560. if (data) {
  8561. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8562. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8563. }
  8564. this._updateBoundingInfo();
  8565. };
  8566. InstancedMesh.prototype._preActivate = function () {
  8567. this.sourceMesh._preActivate();
  8568. };
  8569. InstancedMesh.prototype._activate = function (renderId) {
  8570. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8571. };
  8572. InstancedMesh.prototype._syncSubMeshes = function () {
  8573. this.releaseSubMeshes();
  8574. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8575. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8576. }
  8577. };
  8578. InstancedMesh.prototype._generatePointsArray = function () {
  8579. return this._sourceMesh._generatePointsArray();
  8580. };
  8581. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8582. var result = this._sourceMesh.createInstance(name);
  8583. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8584. this.refreshBoundingInfo();
  8585. if (newParent) {
  8586. result.parent = newParent;
  8587. }
  8588. if (!doNotCloneChildren) {
  8589. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8590. var mesh = this.getScene().meshes[index];
  8591. if (mesh.parent == this) {
  8592. mesh.clone(mesh.name, result);
  8593. }
  8594. }
  8595. }
  8596. result.computeWorldMatrix(true);
  8597. return result;
  8598. };
  8599. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8600. var index = this._sourceMesh.instances.indexOf(this);
  8601. this._sourceMesh.instances.splice(index, 1);
  8602. _super.prototype.dispose.call(this, doNotRecurse);
  8603. };
  8604. return InstancedMesh;
  8605. })(BABYLON.AbstractMesh);
  8606. BABYLON.InstancedMesh = InstancedMesh;
  8607. })(BABYLON || (BABYLON = {}));
  8608. var BABYLON;
  8609. (function (BABYLON) {
  8610. var SubMesh = (function () {
  8611. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8612. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8613. this.materialIndex = materialIndex;
  8614. this.verticesStart = verticesStart;
  8615. this.verticesCount = verticesCount;
  8616. this.indexStart = indexStart;
  8617. this.indexCount = indexCount;
  8618. this._renderId = 0;
  8619. this._mesh = mesh;
  8620. this._renderingMesh = renderingMesh || mesh;
  8621. mesh.subMeshes.push(this);
  8622. this._id = mesh.subMeshes.length - 1;
  8623. if (createBoundingBox) {
  8624. this.refreshBoundingInfo();
  8625. }
  8626. }
  8627. SubMesh.prototype.getBoundingInfo = function () {
  8628. return this._boundingInfo;
  8629. };
  8630. SubMesh.prototype.getMesh = function () {
  8631. return this._mesh;
  8632. };
  8633. SubMesh.prototype.getRenderingMesh = function () {
  8634. return this._renderingMesh;
  8635. };
  8636. SubMesh.prototype.getMaterial = function () {
  8637. var rootMaterial = this._renderingMesh.material;
  8638. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8639. var multiMaterial = rootMaterial;
  8640. return multiMaterial.getSubMaterial(this.materialIndex);
  8641. }
  8642. if (!rootMaterial) {
  8643. return this._mesh.getScene().defaultMaterial;
  8644. }
  8645. return rootMaterial;
  8646. };
  8647. SubMesh.prototype.refreshBoundingInfo = function () {
  8648. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8649. if (!data) {
  8650. this._boundingInfo = this._mesh._boundingInfo;
  8651. return;
  8652. }
  8653. var indices = this._renderingMesh.getIndices();
  8654. var extend;
  8655. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8656. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8657. } else {
  8658. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8659. }
  8660. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8661. };
  8662. SubMesh.prototype._checkCollision = function (collider) {
  8663. return this._boundingInfo._checkCollision(collider);
  8664. };
  8665. SubMesh.prototype.updateBoundingInfo = function (world) {
  8666. if (!this._boundingInfo) {
  8667. this.refreshBoundingInfo();
  8668. }
  8669. this._boundingInfo._update(world);
  8670. };
  8671. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8672. return this._boundingInfo.isInFrustum(frustumPlanes);
  8673. };
  8674. SubMesh.prototype.render = function () {
  8675. this._renderingMesh.render(this);
  8676. };
  8677. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8678. if (!this._linesIndexBuffer) {
  8679. var linesIndices = [];
  8680. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8681. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8682. }
  8683. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8684. this.linesIndexCount = linesIndices.length;
  8685. }
  8686. return this._linesIndexBuffer;
  8687. };
  8688. SubMesh.prototype.canIntersects = function (ray) {
  8689. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8690. };
  8691. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8692. var intersectInfo = null;
  8693. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8694. var p0 = positions[indices[index]];
  8695. var p1 = positions[indices[index + 1]];
  8696. var p2 = positions[indices[index + 2]];
  8697. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8698. if (currentIntersectInfo) {
  8699. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8700. intersectInfo = currentIntersectInfo;
  8701. intersectInfo.faceId = index / 3;
  8702. if (fastCheck) {
  8703. break;
  8704. }
  8705. }
  8706. }
  8707. }
  8708. return intersectInfo;
  8709. };
  8710. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8711. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8712. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8713. return result;
  8714. };
  8715. SubMesh.prototype.dispose = function () {
  8716. if (this._linesIndexBuffer) {
  8717. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8718. this._linesIndexBuffer = null;
  8719. }
  8720. var index = this._mesh.subMeshes.indexOf(this);
  8721. this._mesh.subMeshes.splice(index, 1);
  8722. };
  8723. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8724. var minVertexIndex = Number.MAX_VALUE;
  8725. var maxVertexIndex = -Number.MAX_VALUE;
  8726. renderingMesh = renderingMesh || mesh;
  8727. var indices = renderingMesh.getIndices();
  8728. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8729. var vertexIndex = indices[index];
  8730. if (vertexIndex < minVertexIndex)
  8731. minVertexIndex = vertexIndex;
  8732. if (vertexIndex > maxVertexIndex)
  8733. maxVertexIndex = vertexIndex;
  8734. }
  8735. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8736. };
  8737. return SubMesh;
  8738. })();
  8739. BABYLON.SubMesh = SubMesh;
  8740. })(BABYLON || (BABYLON = {}));
  8741. var BABYLON;
  8742. (function (BABYLON) {
  8743. var BaseTexture = (function () {
  8744. function BaseTexture(scene) {
  8745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8746. this.hasAlpha = false;
  8747. this.getAlphaFromRGB = false;
  8748. this.level = 1;
  8749. this.isCube = false;
  8750. this.isRenderTarget = false;
  8751. this.animations = new Array();
  8752. this.coordinatesIndex = 0;
  8753. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8754. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8755. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8756. this.anisotropicFilteringLevel = 4;
  8757. this._scene = scene;
  8758. this._scene.textures.push(this);
  8759. }
  8760. BaseTexture.prototype.getScene = function () {
  8761. return this._scene;
  8762. };
  8763. BaseTexture.prototype.getTextureMatrix = function () {
  8764. return null;
  8765. };
  8766. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8767. return null;
  8768. };
  8769. BaseTexture.prototype.getInternalTexture = function () {
  8770. return this._texture;
  8771. };
  8772. BaseTexture.prototype.isReady = function () {
  8773. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8774. return true;
  8775. }
  8776. if (this._texture) {
  8777. return this._texture.isReady;
  8778. }
  8779. return false;
  8780. };
  8781. BaseTexture.prototype.getSize = function () {
  8782. if (this._texture._width) {
  8783. return { width: this._texture._width, height: this._texture._height };
  8784. }
  8785. if (this._texture._size) {
  8786. return { width: this._texture._size, height: this._texture._size };
  8787. }
  8788. return { width: 0, height: 0 };
  8789. };
  8790. BaseTexture.prototype.getBaseSize = function () {
  8791. if (!this.isReady())
  8792. return { width: 0, height: 0 };
  8793. if (this._texture._size) {
  8794. return { width: this._texture._size, height: this._texture._size };
  8795. }
  8796. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8797. };
  8798. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8799. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8800. for (var index = 0; index < texturesCache.length; index++) {
  8801. var texturesCacheEntry = texturesCache[index];
  8802. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8803. texturesCacheEntry.references++;
  8804. return texturesCacheEntry;
  8805. }
  8806. }
  8807. return null;
  8808. };
  8809. BaseTexture.prototype.delayLoad = function () {
  8810. };
  8811. BaseTexture.prototype.releaseInternalTexture = function () {
  8812. if (!this._texture) {
  8813. return;
  8814. }
  8815. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8816. this._texture.references--;
  8817. if (this._texture.references == 0) {
  8818. var index = texturesCache.indexOf(this._texture);
  8819. texturesCache.splice(index, 1);
  8820. this._scene.getEngine()._releaseTexture(this._texture);
  8821. delete this._texture;
  8822. }
  8823. };
  8824. BaseTexture.prototype.clone = function () {
  8825. return null;
  8826. };
  8827. BaseTexture.prototype.dispose = function () {
  8828. var index = this._scene.textures.indexOf(this);
  8829. if (index >= 0) {
  8830. this._scene.textures.splice(index, 1);
  8831. }
  8832. if (this._texture === undefined) {
  8833. return;
  8834. }
  8835. this.releaseInternalTexture();
  8836. if (this.onDispose) {
  8837. this.onDispose();
  8838. }
  8839. };
  8840. return BaseTexture;
  8841. })();
  8842. BABYLON.BaseTexture = BaseTexture;
  8843. })(BABYLON || (BABYLON = {}));
  8844. var BABYLON;
  8845. (function (BABYLON) {
  8846. var RenderingGroup = (function () {
  8847. function RenderingGroup(index, scene) {
  8848. this.index = index;
  8849. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8850. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8851. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8852. this._scene = scene;
  8853. }
  8854. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8855. if (customRenderFunction) {
  8856. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8857. return true;
  8858. }
  8859. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8860. return false;
  8861. }
  8862. var engine = this._scene.getEngine();
  8863. var subIndex;
  8864. var submesh;
  8865. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8866. submesh = this._opaqueSubMeshes.data[subIndex];
  8867. this._activeVertices += submesh.verticesCount;
  8868. submesh.render();
  8869. }
  8870. engine.setAlphaTesting(true);
  8871. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8872. submesh = this._alphaTestSubMeshes.data[subIndex];
  8873. this._activeVertices += submesh.verticesCount;
  8874. submesh.render();
  8875. }
  8876. engine.setAlphaTesting(false);
  8877. if (beforeTransparents) {
  8878. beforeTransparents();
  8879. }
  8880. if (this._transparentSubMeshes.length) {
  8881. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8882. submesh = this._transparentSubMeshes.data[subIndex];
  8883. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8884. }
  8885. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8886. sortedArray.sort(function (a, b) {
  8887. if (a._distanceToCamera < b._distanceToCamera) {
  8888. return 1;
  8889. }
  8890. if (a._distanceToCamera > b._distanceToCamera) {
  8891. return -1;
  8892. }
  8893. return 0;
  8894. });
  8895. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8896. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8897. submesh = sortedArray[subIndex];
  8898. this._activeVertices += submesh.verticesCount;
  8899. submesh.render();
  8900. }
  8901. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8902. }
  8903. return true;
  8904. };
  8905. RenderingGroup.prototype.prepare = function () {
  8906. this._opaqueSubMeshes.reset();
  8907. this._transparentSubMeshes.reset();
  8908. this._alphaTestSubMeshes.reset();
  8909. };
  8910. RenderingGroup.prototype.dispatch = function (subMesh) {
  8911. var material = subMesh.getMaterial();
  8912. var mesh = subMesh.getMesh();
  8913. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8914. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8915. this._transparentSubMeshes.push(subMesh);
  8916. }
  8917. } else if (material.needAlphaTesting()) {
  8918. this._alphaTestSubMeshes.push(subMesh);
  8919. } else {
  8920. this._opaqueSubMeshes.push(subMesh);
  8921. }
  8922. };
  8923. return RenderingGroup;
  8924. })();
  8925. BABYLON.RenderingGroup = RenderingGroup;
  8926. })(BABYLON || (BABYLON = {}));
  8927. var BABYLON;
  8928. (function (BABYLON) {
  8929. var RenderingManager = (function () {
  8930. function RenderingManager(scene) {
  8931. this._renderingGroups = new Array();
  8932. this._scene = scene;
  8933. }
  8934. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8935. if (this._scene._activeParticleSystems.length === 0) {
  8936. return;
  8937. }
  8938. var beforeParticlesDate = new Date().getTime();
  8939. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8940. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8941. if (particleSystem.renderingGroupId !== index) {
  8942. continue;
  8943. }
  8944. this._clearDepthBuffer();
  8945. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8946. this._scene._activeParticles += particleSystem.render();
  8947. }
  8948. }
  8949. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8950. };
  8951. RenderingManager.prototype._renderSprites = function (index) {
  8952. if (this._scene.spriteManagers.length === 0) {
  8953. return;
  8954. }
  8955. var beforeSpritessDate = new Date().getTime();
  8956. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8957. var spriteManager = this._scene.spriteManagers[id];
  8958. if (spriteManager.renderingGroupId === index) {
  8959. this._clearDepthBuffer();
  8960. spriteManager.render();
  8961. }
  8962. }
  8963. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8964. };
  8965. RenderingManager.prototype._clearDepthBuffer = function () {
  8966. if (this._depthBufferAlreadyCleaned) {
  8967. return;
  8968. }
  8969. this._scene.getEngine().clear(0, false, true);
  8970. this._depthBufferAlreadyCleaned = true;
  8971. };
  8972. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8973. var _this = this;
  8974. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8975. this._depthBufferAlreadyCleaned = false;
  8976. var renderingGroup = this._renderingGroups[index];
  8977. if (renderingGroup) {
  8978. this._clearDepthBuffer();
  8979. if (!renderingGroup.render(customRenderFunction, function () {
  8980. if (renderSprites) {
  8981. _this._renderSprites(index);
  8982. }
  8983. })) {
  8984. this._renderingGroups.splice(index, 1);
  8985. }
  8986. } else if (renderSprites) {
  8987. this._renderSprites(index);
  8988. }
  8989. if (renderParticles) {
  8990. this._renderParticles(index, activeMeshes);
  8991. }
  8992. }
  8993. };
  8994. RenderingManager.prototype.reset = function () {
  8995. for (var index in this._renderingGroups) {
  8996. var renderingGroup = this._renderingGroups[index];
  8997. renderingGroup.prepare();
  8998. }
  8999. };
  9000. RenderingManager.prototype.dispatch = function (subMesh) {
  9001. var mesh = subMesh.getMesh();
  9002. var renderingGroupId = mesh.renderingGroupId || 0;
  9003. if (!this._renderingGroups[renderingGroupId]) {
  9004. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9005. }
  9006. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9007. };
  9008. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9009. return RenderingManager;
  9010. })();
  9011. BABYLON.RenderingManager = RenderingManager;
  9012. })(BABYLON || (BABYLON = {}));
  9013. var __extends = this.__extends || function (d, b) {
  9014. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9015. function __() { this.constructor = d; }
  9016. __.prototype = b.prototype;
  9017. d.prototype = new __();
  9018. };
  9019. var BABYLON;
  9020. (function (BABYLON) {
  9021. var Texture = (function (_super) {
  9022. __extends(Texture, _super);
  9023. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  9024. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9025. _super.call(this, scene);
  9026. this.uOffset = 0;
  9027. this.vOffset = 0;
  9028. this.uScale = 1.0;
  9029. this.vScale = 1.0;
  9030. this.uAng = 0;
  9031. this.vAng = 0;
  9032. this.wAng = 0;
  9033. this.name = url;
  9034. this.url = url;
  9035. this._noMipmap = noMipmap;
  9036. this._invertY = invertY;
  9037. this._samplingMode = samplingMode;
  9038. if (!url) {
  9039. return;
  9040. }
  9041. this._texture = this._getFromCache(url, noMipmap);
  9042. if (!this._texture) {
  9043. if (!scene.useDelayedTextureLoading) {
  9044. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9045. } else {
  9046. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9047. }
  9048. }
  9049. }
  9050. Texture.prototype.delayLoad = function () {
  9051. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9052. return;
  9053. }
  9054. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9055. this._texture = this._getFromCache(this.url, this._noMipmap);
  9056. if (!this._texture) {
  9057. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9058. }
  9059. };
  9060. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9061. x -= this.uOffset + 0.5;
  9062. y -= this.vOffset + 0.5;
  9063. z -= 0.5;
  9064. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9065. t.x *= this.uScale;
  9066. t.y *= this.vScale;
  9067. t.x += 0.5;
  9068. t.y += 0.5;
  9069. t.z += 0.5;
  9070. };
  9071. Texture.prototype.getTextureMatrix = function () {
  9072. 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) {
  9073. return this._cachedTextureMatrix;
  9074. }
  9075. this._cachedUOffset = this.uOffset;
  9076. this._cachedVOffset = this.vOffset;
  9077. this._cachedUScale = this.uScale;
  9078. this._cachedVScale = this.vScale;
  9079. this._cachedUAng = this.uAng;
  9080. this._cachedVAng = this.vAng;
  9081. this._cachedWAng = this.wAng;
  9082. if (!this._cachedTextureMatrix) {
  9083. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9084. this._rowGenerationMatrix = new BABYLON.Matrix();
  9085. this._t0 = BABYLON.Vector3.Zero();
  9086. this._t1 = BABYLON.Vector3.Zero();
  9087. this._t2 = BABYLON.Vector3.Zero();
  9088. }
  9089. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9090. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9091. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9092. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9093. this._t1.subtractInPlace(this._t0);
  9094. this._t2.subtractInPlace(this._t0);
  9095. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9096. this._cachedTextureMatrix.m[0] = this._t1.x;
  9097. this._cachedTextureMatrix.m[1] = this._t1.y;
  9098. this._cachedTextureMatrix.m[2] = this._t1.z;
  9099. this._cachedTextureMatrix.m[4] = this._t2.x;
  9100. this._cachedTextureMatrix.m[5] = this._t2.y;
  9101. this._cachedTextureMatrix.m[6] = this._t2.z;
  9102. this._cachedTextureMatrix.m[8] = this._t0.x;
  9103. this._cachedTextureMatrix.m[9] = this._t0.y;
  9104. this._cachedTextureMatrix.m[10] = this._t0.z;
  9105. return this._cachedTextureMatrix;
  9106. };
  9107. Texture.prototype.getReflectionTextureMatrix = function () {
  9108. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9109. return this._cachedTextureMatrix;
  9110. }
  9111. if (!this._cachedTextureMatrix) {
  9112. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9113. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9114. }
  9115. switch (this.coordinatesMode) {
  9116. case BABYLON.Texture.SPHERICAL_MODE:
  9117. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9118. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9119. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9120. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9121. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9122. break;
  9123. case BABYLON.Texture.PLANAR_MODE:
  9124. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9125. this._cachedTextureMatrix[0] = this.uScale;
  9126. this._cachedTextureMatrix[5] = this.vScale;
  9127. this._cachedTextureMatrix[12] = this.uOffset;
  9128. this._cachedTextureMatrix[13] = this.vOffset;
  9129. break;
  9130. case BABYLON.Texture.PROJECTION_MODE:
  9131. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9132. this._projectionModeMatrix.m[0] = 0.5;
  9133. this._projectionModeMatrix.m[5] = -0.5;
  9134. this._projectionModeMatrix.m[10] = 0.0;
  9135. this._projectionModeMatrix.m[12] = 0.5;
  9136. this._projectionModeMatrix.m[13] = 0.5;
  9137. this._projectionModeMatrix.m[14] = 1.0;
  9138. this._projectionModeMatrix.m[15] = 1.0;
  9139. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9140. break;
  9141. default:
  9142. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9143. break;
  9144. }
  9145. return this._cachedTextureMatrix;
  9146. };
  9147. Texture.prototype.clone = function () {
  9148. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9149. newTexture.hasAlpha = this.hasAlpha;
  9150. newTexture.level = this.level;
  9151. newTexture.wrapU = this.wrapU;
  9152. newTexture.wrapV = this.wrapV;
  9153. newTexture.coordinatesIndex = this.coordinatesIndex;
  9154. newTexture.coordinatesMode = this.coordinatesMode;
  9155. newTexture.uOffset = this.uOffset;
  9156. newTexture.vOffset = this.vOffset;
  9157. newTexture.uScale = this.uScale;
  9158. newTexture.vScale = this.vScale;
  9159. newTexture.uAng = this.uAng;
  9160. newTexture.vAng = this.vAng;
  9161. newTexture.wAng = this.wAng;
  9162. return newTexture;
  9163. };
  9164. Texture.NEAREST_SAMPLINGMODE = 1;
  9165. Texture.BILINEAR_SAMPLINGMODE = 2;
  9166. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9167. Texture.EXPLICIT_MODE = 0;
  9168. Texture.SPHERICAL_MODE = 1;
  9169. Texture.PLANAR_MODE = 2;
  9170. Texture.CUBIC_MODE = 3;
  9171. Texture.PROJECTION_MODE = 4;
  9172. Texture.SKYBOX_MODE = 5;
  9173. Texture.CLAMP_ADDRESSMODE = 0;
  9174. Texture.WRAP_ADDRESSMODE = 1;
  9175. Texture.MIRROR_ADDRESSMODE = 2;
  9176. return Texture;
  9177. })(BABYLON.BaseTexture);
  9178. BABYLON.Texture = Texture;
  9179. })(BABYLON || (BABYLON = {}));
  9180. var __extends = this.__extends || function (d, b) {
  9181. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9182. function __() { this.constructor = d; }
  9183. __.prototype = b.prototype;
  9184. d.prototype = new __();
  9185. };
  9186. var BABYLON;
  9187. (function (BABYLON) {
  9188. var CubeTexture = (function (_super) {
  9189. __extends(CubeTexture, _super);
  9190. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9191. _super.call(this, scene);
  9192. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9193. this.name = rootUrl;
  9194. this.url = rootUrl;
  9195. this._noMipmap = noMipmap;
  9196. this.hasAlpha = false;
  9197. this._texture = this._getFromCache(rootUrl, noMipmap);
  9198. if (!extensions) {
  9199. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9200. }
  9201. this._extensions = extensions;
  9202. if (!this._texture) {
  9203. if (!scene.useDelayedTextureLoading) {
  9204. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9205. } else {
  9206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9207. }
  9208. }
  9209. this.isCube = true;
  9210. this._textureMatrix = BABYLON.Matrix.Identity();
  9211. }
  9212. CubeTexture.prototype.clone = function () {
  9213. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9214. newTexture.level = this.level;
  9215. newTexture.wrapU = this.wrapU;
  9216. newTexture.wrapV = this.wrapV;
  9217. newTexture.coordinatesIndex = this.coordinatesIndex;
  9218. newTexture.coordinatesMode = this.coordinatesMode;
  9219. return newTexture;
  9220. };
  9221. CubeTexture.prototype.delayLoad = function () {
  9222. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9223. return;
  9224. }
  9225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9226. this._texture = this._getFromCache(this.url, this._noMipmap);
  9227. if (!this._texture) {
  9228. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9229. }
  9230. };
  9231. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9232. return this._textureMatrix;
  9233. };
  9234. return CubeTexture;
  9235. })(BABYLON.BaseTexture);
  9236. BABYLON.CubeTexture = CubeTexture;
  9237. })(BABYLON || (BABYLON = {}));
  9238. var __extends = this.__extends || function (d, b) {
  9239. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9240. function __() { this.constructor = d; }
  9241. __.prototype = b.prototype;
  9242. d.prototype = new __();
  9243. };
  9244. var BABYLON;
  9245. (function (BABYLON) {
  9246. var RenderTargetTexture = (function (_super) {
  9247. __extends(RenderTargetTexture, _super);
  9248. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9249. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9250. _super.call(this, null, scene, !generateMipMaps);
  9251. this.renderList = new Array();
  9252. this.renderParticles = true;
  9253. this.renderSprites = false;
  9254. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9255. this._currentRefreshId = -1;
  9256. this._refreshRate = 1;
  9257. this.name = name;
  9258. this.isRenderTarget = true;
  9259. this._size = size;
  9260. this._generateMipMaps = generateMipMaps;
  9261. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9262. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9263. this._renderingManager = new BABYLON.RenderingManager(scene);
  9264. }
  9265. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9266. this._currentRefreshId = -1;
  9267. };
  9268. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9269. get: function () {
  9270. return this._refreshRate;
  9271. },
  9272. set: function (value) {
  9273. this._refreshRate = value;
  9274. this.resetRefreshCounter();
  9275. },
  9276. enumerable: true,
  9277. configurable: true
  9278. });
  9279. RenderTargetTexture.prototype._shouldRender = function () {
  9280. if (this._currentRefreshId === -1) {
  9281. this._currentRefreshId = 1;
  9282. return true;
  9283. }
  9284. if (this.refreshRate == this._currentRefreshId) {
  9285. this._currentRefreshId = 1;
  9286. return true;
  9287. }
  9288. this._currentRefreshId++;
  9289. return false;
  9290. };
  9291. RenderTargetTexture.prototype.getRenderSize = function () {
  9292. return this._size;
  9293. };
  9294. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9295. this.releaseInternalTexture();
  9296. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9297. };
  9298. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9299. var scene = this.getScene();
  9300. var engine = scene.getEngine();
  9301. if (this._waitingRenderList) {
  9302. this.renderList = [];
  9303. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9304. var id = this._waitingRenderList[index];
  9305. this.renderList.push(scene.getMeshByID(id));
  9306. }
  9307. delete this._waitingRenderList;
  9308. }
  9309. if (!this.renderList) {
  9310. return;
  9311. }
  9312. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9313. engine.bindFramebuffer(this._texture);
  9314. }
  9315. engine.clear(scene.clearColor, true, true);
  9316. this._renderingManager.reset();
  9317. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9318. var mesh = this.renderList[meshIndex];
  9319. if (mesh) {
  9320. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9321. this.resetRefreshCounter();
  9322. continue;
  9323. }
  9324. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9325. mesh._activate(scene.getRenderId());
  9326. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9327. var subMesh = mesh.subMeshes[subIndex];
  9328. scene._activeVertices += subMesh.verticesCount;
  9329. this._renderingManager.dispatch(subMesh);
  9330. }
  9331. }
  9332. }
  9333. }
  9334. if (!this._doNotChangeAspectRatio) {
  9335. scene.updateTransformMatrix(true);
  9336. }
  9337. if (this.onBeforeRender) {
  9338. this.onBeforeRender();
  9339. }
  9340. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9341. if (useCameraPostProcess) {
  9342. scene.postProcessManager._finalizeFrame(false, this._texture);
  9343. }
  9344. if (this.onAfterRender) {
  9345. this.onAfterRender();
  9346. }
  9347. engine.unBindFramebuffer(this._texture);
  9348. if (!this._doNotChangeAspectRatio) {
  9349. scene.updateTransformMatrix(true);
  9350. }
  9351. };
  9352. RenderTargetTexture.prototype.clone = function () {
  9353. var textureSize = this.getSize();
  9354. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9355. newTexture.hasAlpha = this.hasAlpha;
  9356. newTexture.level = this.level;
  9357. newTexture.coordinatesMode = this.coordinatesMode;
  9358. newTexture.renderList = this.renderList.slice(0);
  9359. return newTexture;
  9360. };
  9361. return RenderTargetTexture;
  9362. })(BABYLON.Texture);
  9363. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9364. })(BABYLON || (BABYLON = {}));
  9365. var __extends = this.__extends || function (d, b) {
  9366. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9367. function __() { this.constructor = d; }
  9368. __.prototype = b.prototype;
  9369. d.prototype = new __();
  9370. };
  9371. var BABYLON;
  9372. (function (BABYLON) {
  9373. var MirrorTexture = (function (_super) {
  9374. __extends(MirrorTexture, _super);
  9375. function MirrorTexture(name, size, scene, generateMipMaps) {
  9376. var _this = this;
  9377. _super.call(this, name, size, scene, generateMipMaps, true);
  9378. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9379. this._transformMatrix = BABYLON.Matrix.Zero();
  9380. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9381. this.onBeforeRender = function () {
  9382. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9383. _this._savedViewMatrix = scene.getViewMatrix();
  9384. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9385. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9386. scene.clipPlane = _this.mirrorPlane;
  9387. scene.getEngine().cullBackFaces = false;
  9388. };
  9389. this.onAfterRender = function () {
  9390. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9391. scene.getEngine().cullBackFaces = true;
  9392. delete scene.clipPlane;
  9393. };
  9394. }
  9395. MirrorTexture.prototype.clone = function () {
  9396. var textureSize = this.getSize();
  9397. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9398. newTexture.hasAlpha = this.hasAlpha;
  9399. newTexture.level = this.level;
  9400. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9401. newTexture.renderList = this.renderList.slice(0);
  9402. return newTexture;
  9403. };
  9404. return MirrorTexture;
  9405. })(BABYLON.RenderTargetTexture);
  9406. BABYLON.MirrorTexture = MirrorTexture;
  9407. })(BABYLON || (BABYLON = {}));
  9408. var __extends = this.__extends || function (d, b) {
  9409. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9410. function __() { this.constructor = d; }
  9411. __.prototype = b.prototype;
  9412. d.prototype = new __();
  9413. };
  9414. var BABYLON;
  9415. (function (BABYLON) {
  9416. var DynamicTexture = (function (_super) {
  9417. __extends(DynamicTexture, _super);
  9418. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9419. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9420. _super.call(this, null, scene, !generateMipMaps);
  9421. this.name = name;
  9422. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9423. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9424. this._generateMipMaps = generateMipMaps;
  9425. if (options.getContext) {
  9426. this._canvas = options;
  9427. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9428. } else {
  9429. this._canvas = document.createElement("canvas");
  9430. if (options.width) {
  9431. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9432. } else {
  9433. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9434. }
  9435. }
  9436. var textureSize = this.getSize();
  9437. this._canvas.width = textureSize.width;
  9438. this._canvas.height = textureSize.height;
  9439. this._context = this._canvas.getContext("2d");
  9440. }
  9441. DynamicTexture.prototype.getContext = function () {
  9442. return this._context;
  9443. };
  9444. DynamicTexture.prototype.update = function (invertY) {
  9445. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9446. };
  9447. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9448. var size = this.getSize();
  9449. if (clearColor) {
  9450. this._context.fillStyle = clearColor;
  9451. this._context.fillRect(0, 0, size.width, size.height);
  9452. }
  9453. this._context.font = font;
  9454. if (x === null) {
  9455. var textSize = this._context.measureText(text);
  9456. x = (size.width - textSize.width) / 2;
  9457. }
  9458. this._context.fillStyle = color;
  9459. this._context.fillText(text, x, y);
  9460. this.update(invertY);
  9461. };
  9462. DynamicTexture.prototype.clone = function () {
  9463. var textureSize = this.getSize();
  9464. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9465. newTexture.hasAlpha = this.hasAlpha;
  9466. newTexture.level = this.level;
  9467. newTexture.wrapU = this.wrapU;
  9468. newTexture.wrapV = this.wrapV;
  9469. return newTexture;
  9470. };
  9471. return DynamicTexture;
  9472. })(BABYLON.Texture);
  9473. BABYLON.DynamicTexture = DynamicTexture;
  9474. })(BABYLON || (BABYLON = {}));
  9475. var __extends = this.__extends || function (d, b) {
  9476. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9477. function __() { this.constructor = d; }
  9478. __.prototype = b.prototype;
  9479. d.prototype = new __();
  9480. };
  9481. var BABYLON;
  9482. (function (BABYLON) {
  9483. var VideoTexture = (function (_super) {
  9484. __extends(VideoTexture, _super);
  9485. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9486. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9487. var _this = this;
  9488. _super.call(this, null, scene, !generateMipMaps, invertY);
  9489. this._autoLaunch = true;
  9490. this.name = name;
  9491. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9492. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9493. var requiredWidth = size.width || size;
  9494. var requiredHeight = size.height || size;
  9495. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9496. var textureSize = this.getSize();
  9497. this.video = document.createElement("video");
  9498. this.video.width = textureSize.width;
  9499. this.video.height = textureSize.height;
  9500. this.video.autoplay = false;
  9501. this.video.loop = true;
  9502. this.video.addEventListener("canplaythrough", function () {
  9503. if (_this._texture) {
  9504. _this._texture.isReady = true;
  9505. }
  9506. });
  9507. urls.forEach(function (url) {
  9508. var source = document.createElement("source");
  9509. source.src = url;
  9510. _this.video.appendChild(source);
  9511. });
  9512. this._lastUpdate = new Date().getTime();
  9513. }
  9514. VideoTexture.prototype.update = function () {
  9515. if (this._autoLaunch) {
  9516. this._autoLaunch = false;
  9517. this.video.play();
  9518. }
  9519. var now = new Date().getTime();
  9520. if (now - this._lastUpdate < 15) {
  9521. return false;
  9522. }
  9523. this._lastUpdate = now;
  9524. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9525. return true;
  9526. };
  9527. return VideoTexture;
  9528. })(BABYLON.Texture);
  9529. BABYLON.VideoTexture = VideoTexture;
  9530. })(BABYLON || (BABYLON = {}));
  9531. var BABYLON;
  9532. (function (BABYLON) {
  9533. var EffectFallbacks = (function () {
  9534. function EffectFallbacks() {
  9535. this._defines = {};
  9536. this._currentRank = 32;
  9537. this._maxRank = -1;
  9538. }
  9539. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9540. if (!this._defines[rank]) {
  9541. if (rank < this._currentRank) {
  9542. this._currentRank = rank;
  9543. }
  9544. if (rank > this._maxRank) {
  9545. this._maxRank = rank;
  9546. }
  9547. this._defines[rank] = new Array();
  9548. }
  9549. this._defines[rank].push(define);
  9550. };
  9551. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9552. get: function () {
  9553. return this._currentRank <= this._maxRank;
  9554. },
  9555. enumerable: true,
  9556. configurable: true
  9557. });
  9558. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9559. var currentFallbacks = this._defines[this._currentRank];
  9560. for (var index = 0; index < currentFallbacks.length; index++) {
  9561. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9562. }
  9563. this._currentRank++;
  9564. return currentDefines;
  9565. };
  9566. return EffectFallbacks;
  9567. })();
  9568. BABYLON.EffectFallbacks = EffectFallbacks;
  9569. var Effect = (function () {
  9570. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9571. var _this = this;
  9572. this._isReady = false;
  9573. this._compilationError = "";
  9574. this._valueCache = [];
  9575. this._engine = engine;
  9576. this.name = baseName;
  9577. this.defines = defines;
  9578. this._uniformsNames = uniformsNames.concat(samplers);
  9579. this._samplers = samplers;
  9580. this._attributesNames = attributesNames;
  9581. this.onError = onError;
  9582. this.onCompiled = onCompiled;
  9583. var vertexSource;
  9584. var fragmentSource;
  9585. if (baseName.vertexElement) {
  9586. vertexSource = document.getElementById(baseName.vertexElement);
  9587. } else {
  9588. vertexSource = baseName.vertex || baseName;
  9589. }
  9590. if (baseName.fragmentElement) {
  9591. fragmentSource = document.getElementById(baseName.fragmentElement);
  9592. } else {
  9593. fragmentSource = baseName.fragment || baseName;
  9594. }
  9595. this._loadVertexShader(vertexSource, function (vertexCode) {
  9596. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9597. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9598. });
  9599. });
  9600. }
  9601. Effect.prototype.isReady = function () {
  9602. return this._isReady;
  9603. };
  9604. Effect.prototype.getProgram = function () {
  9605. return this._program;
  9606. };
  9607. Effect.prototype.getAttributesNames = function () {
  9608. return this._attributesNames;
  9609. };
  9610. Effect.prototype.getAttributeLocation = function (index) {
  9611. return this._attributes[index];
  9612. };
  9613. Effect.prototype.getAttributeLocationByName = function (name) {
  9614. var index = this._attributesNames.indexOf(name);
  9615. return this._attributes[index];
  9616. };
  9617. Effect.prototype.getAttributesCount = function () {
  9618. return this._attributes.length;
  9619. };
  9620. Effect.prototype.getUniformIndex = function (uniformName) {
  9621. return this._uniformsNames.indexOf(uniformName);
  9622. };
  9623. Effect.prototype.getUniform = function (uniformName) {
  9624. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9625. };
  9626. Effect.prototype.getSamplers = function () {
  9627. return this._samplers;
  9628. };
  9629. Effect.prototype.getCompilationError = function () {
  9630. return this._compilationError;
  9631. };
  9632. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9633. if (vertex instanceof HTMLElement) {
  9634. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9635. callback(vertexCode);
  9636. return;
  9637. }
  9638. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9639. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9640. return;
  9641. }
  9642. var vertexShaderUrl;
  9643. if (vertex[0] === ".") {
  9644. vertexShaderUrl = vertex;
  9645. } else {
  9646. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9647. }
  9648. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9649. };
  9650. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9651. if (fragment instanceof HTMLElement) {
  9652. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9653. callback(fragmentCode);
  9654. return;
  9655. }
  9656. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9657. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9658. return;
  9659. }
  9660. var fragmentShaderUrl;
  9661. if (fragment[0] === ".") {
  9662. fragmentShaderUrl = fragment;
  9663. } else {
  9664. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9665. }
  9666. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9667. };
  9668. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9669. try {
  9670. var engine = this._engine;
  9671. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9672. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9673. this._attributes = engine.getAttributes(this._program, attributesNames);
  9674. for (var index = 0; index < this._samplers.length; index++) {
  9675. var sampler = this.getUniform(this._samplers[index]);
  9676. if (sampler == null) {
  9677. this._samplers.splice(index, 1);
  9678. index--;
  9679. }
  9680. }
  9681. engine.bindSamplers(this);
  9682. this._isReady = true;
  9683. if (this.onCompiled) {
  9684. this.onCompiled(this);
  9685. }
  9686. } catch (e) {
  9687. if (fallbacks && fallbacks.isMoreFallbacks) {
  9688. defines = fallbacks.reduce(defines);
  9689. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9690. } else {
  9691. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9692. BABYLON.Tools.Error("Defines: " + defines);
  9693. BABYLON.Tools.Error("Error: " + e.message);
  9694. this._compilationError = e.message;
  9695. if (this.onError) {
  9696. this.onError(this, this._compilationError);
  9697. }
  9698. }
  9699. }
  9700. };
  9701. Effect.prototype._bindTexture = function (channel, texture) {
  9702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9703. };
  9704. Effect.prototype.setTexture = function (channel, texture) {
  9705. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9706. };
  9707. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9708. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9709. };
  9710. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9711. if (!this._valueCache[uniformName]) {
  9712. this._valueCache[uniformName] = [x, y];
  9713. return;
  9714. }
  9715. this._valueCache[uniformName][0] = x;
  9716. this._valueCache[uniformName][1] = y;
  9717. };
  9718. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9719. if (!this._valueCache[uniformName]) {
  9720. this._valueCache[uniformName] = [x, y, z];
  9721. return;
  9722. }
  9723. this._valueCache[uniformName][0] = x;
  9724. this._valueCache[uniformName][1] = y;
  9725. this._valueCache[uniformName][2] = z;
  9726. };
  9727. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9728. if (!this._valueCache[uniformName]) {
  9729. this._valueCache[uniformName] = [x, y, z, w];
  9730. return;
  9731. }
  9732. this._valueCache[uniformName][0] = x;
  9733. this._valueCache[uniformName][1] = y;
  9734. this._valueCache[uniformName][2] = z;
  9735. this._valueCache[uniformName][3] = w;
  9736. };
  9737. Effect.prototype.setArray = function (uniformName, array) {
  9738. this._engine.setArray(this.getUniform(uniformName), array);
  9739. return this;
  9740. };
  9741. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9742. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9743. return this;
  9744. };
  9745. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9747. return this;
  9748. };
  9749. Effect.prototype.setFloat = function (uniformName, value) {
  9750. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9751. return this;
  9752. this._valueCache[uniformName] = value;
  9753. this._engine.setFloat(this.getUniform(uniformName), value);
  9754. return this;
  9755. };
  9756. Effect.prototype.setBool = function (uniformName, bool) {
  9757. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9758. return this;
  9759. this._valueCache[uniformName] = bool;
  9760. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9761. return this;
  9762. };
  9763. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9764. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9765. return this;
  9766. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9767. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9768. return this;
  9769. };
  9770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9771. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9772. return this;
  9773. this._cacheFloat2(uniformName, x, y);
  9774. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9775. return this;
  9776. };
  9777. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9778. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9779. return this;
  9780. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9781. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9782. return this;
  9783. };
  9784. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9785. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9786. return this;
  9787. this._cacheFloat3(uniformName, x, y, z);
  9788. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9789. return this;
  9790. };
  9791. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9792. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9793. return this;
  9794. this._cacheFloat4(uniformName, x, y, z, w);
  9795. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9796. return this;
  9797. };
  9798. Effect.prototype.setColor3 = function (uniformName, color3) {
  9799. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9800. return this;
  9801. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9802. this._engine.setColor3(this.getUniform(uniformName), color3);
  9803. return this;
  9804. };
  9805. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9806. 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)
  9807. return this;
  9808. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9809. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9810. return this;
  9811. };
  9812. 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}",
  9813. 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}",
  9814. 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}",
  9815. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9816. 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}",
  9817. 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}",
  9818. 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}",
  9819. 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}",
  9820. 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}",
  9821. 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}",
  9822. 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}",
  9823. 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}",
  9824. 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}",
  9825. 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}",
  9826. 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}",
  9827. 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}",
  9828. 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}",
  9829. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\n\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  9830. 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}",
  9831. 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}",
  9832. 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}",
  9833. 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}",
  9834. 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}",
  9835. 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}",
  9836. 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}",
  9837. 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}",
  9838. 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}",
  9839. 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}",
  9840. 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}",
  9841. };
  9842. return Effect;
  9843. })();
  9844. BABYLON.Effect = Effect;
  9845. })(BABYLON || (BABYLON = {}));
  9846. var BABYLON;
  9847. (function (BABYLON) {
  9848. var Material = (function () {
  9849. function Material(name, scene, doNotAdd) {
  9850. this.name = name;
  9851. this.checkReadyOnEveryCall = true;
  9852. this.checkReadyOnlyOnce = false;
  9853. this.state = "";
  9854. this.alpha = 1.0;
  9855. this.wireframe = false;
  9856. this.backFaceCulling = true;
  9857. this._wasPreviouslyReady = false;
  9858. this.id = name;
  9859. this._scene = scene;
  9860. if (!doNotAdd) {
  9861. scene.materials.push(this);
  9862. }
  9863. }
  9864. Material.prototype.isReady = function (mesh, useInstances) {
  9865. return true;
  9866. };
  9867. Material.prototype.getEffect = function () {
  9868. return this._effect;
  9869. };
  9870. Material.prototype.getScene = function () {
  9871. return this._scene;
  9872. };
  9873. Material.prototype.needAlphaBlending = function () {
  9874. return (this.alpha < 1.0);
  9875. };
  9876. Material.prototype.needAlphaTesting = function () {
  9877. return false;
  9878. };
  9879. Material.prototype.getAlphaTestTexture = function () {
  9880. return null;
  9881. };
  9882. Material.prototype.trackCreation = function (onCompiled, onError) {
  9883. };
  9884. Material.prototype._preBind = function () {
  9885. var engine = this._scene.getEngine();
  9886. engine.enableEffect(this._effect);
  9887. engine.setState(this.backFaceCulling);
  9888. };
  9889. Material.prototype.bind = function (world, mesh) {
  9890. };
  9891. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9892. };
  9893. Material.prototype.unbind = function () {
  9894. };
  9895. Material.prototype.dispose = function (forceDisposeEffect) {
  9896. var index = this._scene.materials.indexOf(this);
  9897. this._scene.materials.splice(index, 1);
  9898. if (forceDisposeEffect && this._effect) {
  9899. this._scene.getEngine()._releaseEffect(this._effect);
  9900. this._effect = null;
  9901. }
  9902. if (this.onDispose) {
  9903. this.onDispose();
  9904. }
  9905. };
  9906. return Material;
  9907. })();
  9908. BABYLON.Material = Material;
  9909. })(BABYLON || (BABYLON = {}));
  9910. var __extends = this.__extends || function (d, b) {
  9911. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9912. function __() { this.constructor = d; }
  9913. __.prototype = b.prototype;
  9914. d.prototype = new __();
  9915. };
  9916. var BABYLON;
  9917. (function (BABYLON) {
  9918. var maxSimultaneousLights = 4;
  9919. var FresnelParameters = (function () {
  9920. function FresnelParameters() {
  9921. this.isEnabled = true;
  9922. this.leftColor = BABYLON.Color3.White();
  9923. this.rightColor = BABYLON.Color3.Black();
  9924. this.bias = 0;
  9925. this.power = 1;
  9926. }
  9927. return FresnelParameters;
  9928. })();
  9929. BABYLON.FresnelParameters = FresnelParameters;
  9930. var StandardMaterial = (function (_super) {
  9931. __extends(StandardMaterial, _super);
  9932. function StandardMaterial(name, scene) {
  9933. var _this = this;
  9934. _super.call(this, name, scene);
  9935. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9936. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9937. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9938. this.specularPower = 64;
  9939. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9940. this.useAlphaFromDiffuseTexture = false;
  9941. this.useSpecularOverAlpha = true;
  9942. this._cachedDefines = null;
  9943. this._renderTargets = new BABYLON.SmartArray(16);
  9944. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9945. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9946. this._scaledDiffuse = new BABYLON.Color3();
  9947. this._scaledSpecular = new BABYLON.Color3();
  9948. this.getRenderTargetTextures = function () {
  9949. _this._renderTargets.reset();
  9950. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9951. _this._renderTargets.push(_this.reflectionTexture);
  9952. }
  9953. return _this._renderTargets;
  9954. };
  9955. }
  9956. StandardMaterial.prototype.needAlphaBlending = function () {
  9957. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  9958. };
  9959. StandardMaterial.prototype.needAlphaTesting = function () {
  9960. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9961. };
  9962. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9963. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9964. };
  9965. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9966. return this.diffuseTexture;
  9967. };
  9968. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9969. if (this.checkReadyOnlyOnce) {
  9970. if (this._wasPreviouslyReady) {
  9971. return true;
  9972. }
  9973. }
  9974. var scene = this.getScene();
  9975. if (!this.checkReadyOnEveryCall) {
  9976. if (this._renderId === scene.getRenderId()) {
  9977. return true;
  9978. }
  9979. }
  9980. var engine = scene.getEngine();
  9981. var defines = [];
  9982. var fallbacks = new BABYLON.EffectFallbacks();
  9983. if (scene.texturesEnabled) {
  9984. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  9985. if (!this.diffuseTexture.isReady()) {
  9986. return false;
  9987. } else {
  9988. defines.push("#define DIFFUSE");
  9989. }
  9990. }
  9991. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  9992. if (!this.ambientTexture.isReady()) {
  9993. return false;
  9994. } else {
  9995. defines.push("#define AMBIENT");
  9996. }
  9997. }
  9998. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  9999. if (!this.opacityTexture.isReady()) {
  10000. return false;
  10001. } else {
  10002. defines.push("#define OPACITY");
  10003. if (this.opacityTexture.getAlphaFromRGB) {
  10004. defines.push("#define OPACITYRGB");
  10005. }
  10006. }
  10007. }
  10008. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10009. if (!this.reflectionTexture.isReady()) {
  10010. return false;
  10011. } else {
  10012. defines.push("#define REFLECTION");
  10013. fallbacks.addFallback(0, "REFLECTION");
  10014. }
  10015. }
  10016. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10017. if (!this.emissiveTexture.isReady()) {
  10018. return false;
  10019. } else {
  10020. defines.push("#define EMISSIVE");
  10021. }
  10022. }
  10023. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10024. if (!this.specularTexture.isReady()) {
  10025. return false;
  10026. } else {
  10027. defines.push("#define SPECULAR");
  10028. fallbacks.addFallback(0, "SPECULAR");
  10029. }
  10030. }
  10031. }
  10032. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10033. if (!this.bumpTexture.isReady()) {
  10034. return false;
  10035. } else {
  10036. defines.push("#define BUMP");
  10037. fallbacks.addFallback(0, "BUMP");
  10038. }
  10039. }
  10040. if (this.useSpecularOverAlpha) {
  10041. defines.push("#define SPECULAROVERALPHA");
  10042. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10043. }
  10044. if (scene.clipPlane) {
  10045. defines.push("#define CLIPPLANE");
  10046. }
  10047. if (engine.getAlphaTesting()) {
  10048. defines.push("#define ALPHATEST");
  10049. }
  10050. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10051. defines.push("#define ALPHAFROMDIFFUSE");
  10052. }
  10053. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10054. defines.push("#define FOG");
  10055. fallbacks.addFallback(1, "FOG");
  10056. }
  10057. var shadowsActivated = false;
  10058. var lightIndex = 0;
  10059. if (scene.lightsEnabled) {
  10060. for (var index = 0; index < scene.lights.length; index++) {
  10061. var light = scene.lights[index];
  10062. if (!light.isEnabled()) {
  10063. continue;
  10064. }
  10065. if (light._excludedMeshesIds.length > 0) {
  10066. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10067. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10068. if (excludedMesh) {
  10069. light.excludedMeshes.push(excludedMesh);
  10070. }
  10071. }
  10072. light._excludedMeshesIds = [];
  10073. }
  10074. if (light._includedOnlyMeshesIds.length > 0) {
  10075. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10076. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10077. if (includedOnlyMesh) {
  10078. light.includedOnlyMeshes.push(includedOnlyMesh);
  10079. }
  10080. }
  10081. light._includedOnlyMeshesIds = [];
  10082. }
  10083. if (!light.canAffectMesh(mesh)) {
  10084. continue;
  10085. }
  10086. defines.push("#define LIGHT" + lightIndex);
  10087. if (lightIndex > 0) {
  10088. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10089. }
  10090. var type;
  10091. if (light instanceof BABYLON.SpotLight) {
  10092. type = "#define SPOTLIGHT" + lightIndex;
  10093. } else if (light instanceof BABYLON.HemisphericLight) {
  10094. type = "#define HEMILIGHT" + lightIndex;
  10095. } else {
  10096. type = "#define POINTDIRLIGHT" + lightIndex;
  10097. }
  10098. defines.push(type);
  10099. if (lightIndex > 0) {
  10100. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10101. }
  10102. var shadowGenerator = light.getShadowGenerator();
  10103. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10104. defines.push("#define SHADOW" + lightIndex);
  10105. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10106. if (!shadowsActivated) {
  10107. defines.push("#define SHADOWS");
  10108. shadowsActivated = true;
  10109. }
  10110. if (shadowGenerator.useVarianceShadowMap) {
  10111. defines.push("#define SHADOWVSM" + lightIndex);
  10112. if (lightIndex > 0) {
  10113. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10114. }
  10115. }
  10116. if (shadowGenerator.usePoissonSampling) {
  10117. defines.push("#define SHADOWPCF" + lightIndex);
  10118. if (lightIndex > 0) {
  10119. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10120. }
  10121. }
  10122. }
  10123. lightIndex++;
  10124. if (lightIndex == maxSimultaneousLights)
  10125. break;
  10126. }
  10127. }
  10128. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10129. var fresnelRank = 1;
  10130. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10131. defines.push("#define DIFFUSEFRESNEL");
  10132. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10133. fresnelRank++;
  10134. }
  10135. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10136. defines.push("#define OPACITYFRESNEL");
  10137. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10138. fresnelRank++;
  10139. }
  10140. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10141. defines.push("#define REFLECTIONFRESNEL");
  10142. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10143. fresnelRank++;
  10144. }
  10145. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10146. defines.push("#define EMISSIVEFRESNEL");
  10147. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10148. fresnelRank++;
  10149. }
  10150. defines.push("#define FRESNEL");
  10151. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10152. }
  10153. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10154. if (mesh) {
  10155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10156. attribs.push(BABYLON.VertexBuffer.UVKind);
  10157. defines.push("#define UV1");
  10158. }
  10159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10160. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10161. defines.push("#define UV2");
  10162. }
  10163. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10164. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10165. defines.push("#define VERTEXCOLOR");
  10166. }
  10167. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10168. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10169. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10170. defines.push("#define BONES");
  10171. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10172. defines.push("#define BONES4");
  10173. fallbacks.addFallback(0, "BONES4");
  10174. }
  10175. if (useInstances) {
  10176. defines.push("#define INSTANCES");
  10177. attribs.push("world0");
  10178. attribs.push("world1");
  10179. attribs.push("world2");
  10180. attribs.push("world3");
  10181. }
  10182. }
  10183. var join = defines.join("\n");
  10184. if (this._cachedDefines != join) {
  10185. this._cachedDefines = join;
  10186. var shaderName = "default";
  10187. if (!scene.getEngine().getCaps().standardDerivatives) {
  10188. shaderName = "legacydefault";
  10189. }
  10190. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10191. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10192. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10193. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10194. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10195. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10196. "vFogInfos", "vFogColor",
  10197. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10198. "mBones",
  10199. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10200. "darkness0", "darkness1", "darkness2", "darkness3",
  10201. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10202. ], [
  10203. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10204. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10205. ], join, fallbacks, this.onCompiled, this.onError);
  10206. }
  10207. if (!this._effect.isReady()) {
  10208. return false;
  10209. }
  10210. this._renderId = scene.getRenderId();
  10211. this._wasPreviouslyReady = true;
  10212. return true;
  10213. };
  10214. StandardMaterial.prototype.unbind = function () {
  10215. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10216. this._effect.setTexture("reflection2DSampler", null);
  10217. }
  10218. };
  10219. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10220. this._effect.setMatrix("world", world);
  10221. };
  10222. StandardMaterial.prototype.bind = function (world, mesh) {
  10223. var scene = this.getScene();
  10224. this.bindOnlyWorldMatrix(world);
  10225. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10226. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10227. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10228. }
  10229. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10230. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10231. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10232. }
  10233. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10234. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10235. }
  10236. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10237. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10238. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10239. }
  10240. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10241. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10242. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10243. }
  10244. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10245. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10246. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10247. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10248. }
  10249. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10250. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10251. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10252. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10253. }
  10254. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10255. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10256. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10257. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10258. }
  10259. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10260. if (this.reflectionTexture.isCube) {
  10261. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10262. } else {
  10263. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10264. }
  10265. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10266. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10267. }
  10268. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10269. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10270. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10271. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10272. }
  10273. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10274. this._effect.setTexture("specularSampler", this.specularTexture);
  10275. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10276. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10277. }
  10278. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10279. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10280. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10281. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10282. }
  10283. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10284. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10285. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10286. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10287. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10288. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10289. if (scene.lightsEnabled) {
  10290. var lightIndex = 0;
  10291. for (var index = 0; index < scene.lights.length; index++) {
  10292. var light = scene.lights[index];
  10293. if (!light.isEnabled()) {
  10294. continue;
  10295. }
  10296. if (!light.canAffectMesh(mesh)) {
  10297. continue;
  10298. }
  10299. if (light instanceof BABYLON.PointLight) {
  10300. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10301. } else if (light instanceof BABYLON.DirectionalLight) {
  10302. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10303. } else if (light instanceof BABYLON.SpotLight) {
  10304. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10305. } else if (light instanceof BABYLON.HemisphericLight) {
  10306. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10307. }
  10308. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10309. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10310. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10311. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10312. var shadowGenerator = light.getShadowGenerator();
  10313. if (mesh.receiveShadows && shadowGenerator) {
  10314. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10315. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10316. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10317. }
  10318. lightIndex++;
  10319. if (lightIndex == maxSimultaneousLights)
  10320. break;
  10321. }
  10322. }
  10323. if (scene.clipPlane) {
  10324. var clipPlane = scene.clipPlane;
  10325. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10326. }
  10327. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10328. this._effect.setMatrix("view", scene.getViewMatrix());
  10329. }
  10330. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10331. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10332. this._effect.setColor3("vFogColor", scene.fogColor);
  10333. }
  10334. };
  10335. StandardMaterial.prototype.getAnimatables = function () {
  10336. var results = [];
  10337. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10338. results.push(this.diffuseTexture);
  10339. }
  10340. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10341. results.push(this.ambientTexture);
  10342. }
  10343. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10344. results.push(this.opacityTexture);
  10345. }
  10346. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10347. results.push(this.reflectionTexture);
  10348. }
  10349. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10350. results.push(this.emissiveTexture);
  10351. }
  10352. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10353. results.push(this.specularTexture);
  10354. }
  10355. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10356. results.push(this.bumpTexture);
  10357. }
  10358. return results;
  10359. };
  10360. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10361. if (this.diffuseTexture) {
  10362. this.diffuseTexture.dispose();
  10363. }
  10364. if (this.ambientTexture) {
  10365. this.ambientTexture.dispose();
  10366. }
  10367. if (this.opacityTexture) {
  10368. this.opacityTexture.dispose();
  10369. }
  10370. if (this.reflectionTexture) {
  10371. this.reflectionTexture.dispose();
  10372. }
  10373. if (this.emissiveTexture) {
  10374. this.emissiveTexture.dispose();
  10375. }
  10376. if (this.specularTexture) {
  10377. this.specularTexture.dispose();
  10378. }
  10379. if (this.bumpTexture) {
  10380. this.bumpTexture.dispose();
  10381. }
  10382. _super.prototype.dispose.call(this, forceDisposeEffect);
  10383. };
  10384. StandardMaterial.prototype.clone = function (name) {
  10385. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10386. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10387. newStandardMaterial.alpha = this.alpha;
  10388. newStandardMaterial.wireframe = this.wireframe;
  10389. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10390. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10391. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10392. }
  10393. if (this.ambientTexture && this.ambientTexture.clone) {
  10394. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10395. }
  10396. if (this.opacityTexture && this.opacityTexture.clone) {
  10397. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10398. }
  10399. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10400. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10401. }
  10402. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10403. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10404. }
  10405. if (this.specularTexture && this.specularTexture.clone) {
  10406. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10407. }
  10408. if (this.bumpTexture && this.bumpTexture.clone) {
  10409. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10410. }
  10411. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10412. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10413. newStandardMaterial.specularColor = this.specularColor.clone();
  10414. newStandardMaterial.specularPower = this.specularPower;
  10415. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10416. return newStandardMaterial;
  10417. };
  10418. StandardMaterial.DiffuseTextureEnabled = true;
  10419. StandardMaterial.AmbientTextureEnabled = true;
  10420. StandardMaterial.OpacityTextureEnabled = true;
  10421. StandardMaterial.ReflectionTextureEnabled = true;
  10422. StandardMaterial.EmissiveTextureEnabled = true;
  10423. StandardMaterial.SpecularTextureEnabled = true;
  10424. StandardMaterial.BumpTextureEnabled = true;
  10425. return StandardMaterial;
  10426. })(BABYLON.Material);
  10427. BABYLON.StandardMaterial = StandardMaterial;
  10428. })(BABYLON || (BABYLON = {}));
  10429. var __extends = this.__extends || function (d, b) {
  10430. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10431. function __() { this.constructor = d; }
  10432. __.prototype = b.prototype;
  10433. d.prototype = new __();
  10434. };
  10435. var BABYLON;
  10436. (function (BABYLON) {
  10437. var MultiMaterial = (function (_super) {
  10438. __extends(MultiMaterial, _super);
  10439. function MultiMaterial(name, scene) {
  10440. _super.call(this, name, scene, true);
  10441. this.subMaterials = new Array();
  10442. scene.multiMaterials.push(this);
  10443. }
  10444. MultiMaterial.prototype.getSubMaterial = function (index) {
  10445. if (index < 0 || index >= this.subMaterials.length) {
  10446. return this.getScene().defaultMaterial;
  10447. }
  10448. return this.subMaterials[index];
  10449. };
  10450. MultiMaterial.prototype.isReady = function (mesh) {
  10451. for (var index = 0; index < this.subMaterials.length; index++) {
  10452. var subMaterial = this.subMaterials[index];
  10453. if (subMaterial) {
  10454. if (!this.subMaterials[index].isReady(mesh)) {
  10455. return false;
  10456. }
  10457. }
  10458. }
  10459. return true;
  10460. };
  10461. return MultiMaterial;
  10462. })(BABYLON.Material);
  10463. BABYLON.MultiMaterial = MultiMaterial;
  10464. })(BABYLON || (BABYLON = {}));
  10465. var BABYLON;
  10466. (function (BABYLON) {
  10467. var Database = (function () {
  10468. function Database(urlToScene, callbackManifestChecked) {
  10469. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10470. this.callbackManifestChecked = callbackManifestChecked;
  10471. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10472. this.db = null;
  10473. this.enableSceneOffline = false;
  10474. this.enableTexturesOffline = false;
  10475. this.manifestVersionFound = 0;
  10476. this.mustUpdateRessources = false;
  10477. this.hasReachedQuota = false;
  10478. this.checkManifestFile();
  10479. }
  10480. Database.prototype.checkManifestFile = function () {
  10481. var _this = this;
  10482. function noManifestFile() {
  10483. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10484. that.enableSceneOffline = false;
  10485. that.enableTexturesOffline = false;
  10486. that.callbackManifestChecked(false);
  10487. }
  10488. var that = this;
  10489. var manifestURL = this.currentSceneUrl + ".manifest";
  10490. var xhr = new XMLHttpRequest();
  10491. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10492. xhr.open("GET", manifestURLTimeStamped, true);
  10493. xhr.addEventListener("load", function () {
  10494. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10495. try {
  10496. var manifestFile = JSON.parse(xhr.response);
  10497. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10498. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10499. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10500. _this.manifestVersionFound = manifestFile.version;
  10501. }
  10502. if (_this.callbackManifestChecked) {
  10503. _this.callbackManifestChecked(true);
  10504. }
  10505. } catch (ex) {
  10506. noManifestFile();
  10507. }
  10508. } else {
  10509. noManifestFile();
  10510. }
  10511. }, false);
  10512. xhr.addEventListener("error", function (event) {
  10513. noManifestFile();
  10514. }, false);
  10515. try {
  10516. xhr.send();
  10517. } catch (ex) {
  10518. BABYLON.Tools.Error("Error on XHR send request.");
  10519. that.callbackManifestChecked(false);
  10520. }
  10521. };
  10522. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10523. var _this = this;
  10524. function handleError() {
  10525. that.isSupported = false;
  10526. if (errorCallback)
  10527. errorCallback();
  10528. }
  10529. var that = this;
  10530. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10531. this.isSupported = false;
  10532. if (errorCallback)
  10533. errorCallback();
  10534. } else {
  10535. if (!this.db) {
  10536. this.hasReachedQuota = false;
  10537. this.isSupported = true;
  10538. var request = this.idbFactory.open("babylonjs", 1);
  10539. request.onerror = function (event) {
  10540. handleError();
  10541. };
  10542. request.onblocked = function (event) {
  10543. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10544. handleError();
  10545. };
  10546. request.onsuccess = function (event) {
  10547. _this.db = request.result;
  10548. successCallback();
  10549. };
  10550. request.onupgradeneeded = function (event) {
  10551. _this.db = (event.target).result;
  10552. try {
  10553. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10554. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10555. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10556. } catch (ex) {
  10557. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10558. handleError();
  10559. }
  10560. };
  10561. } else {
  10562. if (successCallback)
  10563. successCallback();
  10564. }
  10565. }
  10566. };
  10567. Database.prototype.loadImageFromDB = function (url, image) {
  10568. var _this = this;
  10569. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10570. var saveAndLoadImage = function () {
  10571. if (!_this.hasReachedQuota && _this.db !== null) {
  10572. _this._saveImageIntoDBAsync(completeURL, image);
  10573. } else {
  10574. image.src = url;
  10575. }
  10576. };
  10577. if (!this.mustUpdateRessources) {
  10578. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10579. } else {
  10580. saveAndLoadImage();
  10581. }
  10582. };
  10583. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10584. if (this.isSupported && this.db !== null) {
  10585. var texture;
  10586. var transaction = this.db.transaction(["textures"]);
  10587. transaction.onabort = function (event) {
  10588. image.src = url;
  10589. };
  10590. transaction.oncomplete = function (event) {
  10591. var blobTextureURL;
  10592. if (texture) {
  10593. var URL = window.URL || window.webkitURL;
  10594. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10595. image.onerror = function () {
  10596. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10597. image.src = url;
  10598. };
  10599. image.src = blobTextureURL;
  10600. } else {
  10601. notInDBCallback();
  10602. }
  10603. };
  10604. var getRequest = transaction.objectStore("textures").get(url);
  10605. getRequest.onsuccess = function (event) {
  10606. texture = (event.target).result;
  10607. };
  10608. getRequest.onerror = function (event) {
  10609. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10610. image.src = url;
  10611. };
  10612. } else {
  10613. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10614. image.src = url;
  10615. }
  10616. };
  10617. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10618. var _this = this;
  10619. if (this.isSupported) {
  10620. var generateBlobUrl = function () {
  10621. var blobTextureURL;
  10622. if (blob) {
  10623. var URL = window.URL || window.webkitURL;
  10624. try {
  10625. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10626. } catch (ex) {
  10627. blobTextureURL = URL.createObjectURL(blob);
  10628. }
  10629. }
  10630. image.src = blobTextureURL;
  10631. };
  10632. if (BABYLON.Database.isUASupportingBlobStorage) {
  10633. var xhr = new XMLHttpRequest(), blob;
  10634. xhr.open("GET", url, true);
  10635. xhr.responseType = "blob";
  10636. xhr.addEventListener("load", function () {
  10637. if (xhr.status === 200) {
  10638. blob = xhr.response;
  10639. var transaction = _this.db.transaction(["textures"], "readwrite");
  10640. transaction.onabort = function (event) {
  10641. try {
  10642. if (event.srcElement.error.name === "QuotaExceededError") {
  10643. this.hasReachedQuota = true;
  10644. }
  10645. } catch (ex) {
  10646. }
  10647. generateBlobUrl();
  10648. };
  10649. transaction.oncomplete = function (event) {
  10650. generateBlobUrl();
  10651. };
  10652. var newTexture = { textureUrl: url, data: blob };
  10653. try {
  10654. var addRequest = transaction.objectStore("textures").put(newTexture);
  10655. addRequest.onsuccess = function (event) {
  10656. };
  10657. addRequest.onerror = function (event) {
  10658. generateBlobUrl();
  10659. };
  10660. } catch (ex) {
  10661. if (ex.code === 25) {
  10662. BABYLON.Database.isUASupportingBlobStorage = false;
  10663. }
  10664. image.src = url;
  10665. }
  10666. } else {
  10667. image.src = url;
  10668. }
  10669. }, false);
  10670. xhr.addEventListener("error", function (event) {
  10671. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10672. image.src = url;
  10673. }, false);
  10674. xhr.send();
  10675. } else {
  10676. image.src = url;
  10677. }
  10678. } else {
  10679. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10680. image.src = url;
  10681. }
  10682. };
  10683. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10684. var _this = this;
  10685. var updateVersion = function (event) {
  10686. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10687. };
  10688. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10689. };
  10690. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10691. var _this = this;
  10692. if (this.isSupported) {
  10693. var version;
  10694. try {
  10695. var transaction = this.db.transaction(["versions"]);
  10696. transaction.oncomplete = function (event) {
  10697. if (version) {
  10698. if (_this.manifestVersionFound > version.data) {
  10699. _this.mustUpdateRessources = true;
  10700. updateInDBCallback();
  10701. } else {
  10702. callback(version.data);
  10703. }
  10704. } else {
  10705. _this.mustUpdateRessources = true;
  10706. updateInDBCallback();
  10707. }
  10708. };
  10709. transaction.onabort = function (event) {
  10710. callback(-1);
  10711. };
  10712. var getRequest = transaction.objectStore("versions").get(url);
  10713. getRequest.onsuccess = function (event) {
  10714. version = (event.target).result;
  10715. };
  10716. getRequest.onerror = function (event) {
  10717. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10718. callback(-1);
  10719. };
  10720. } catch (ex) {
  10721. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10722. callback(-1);
  10723. }
  10724. } else {
  10725. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10726. callback(-1);
  10727. }
  10728. };
  10729. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10730. var _this = this;
  10731. if (this.isSupported && !this.hasReachedQuota) {
  10732. try {
  10733. var transaction = this.db.transaction(["versions"], "readwrite");
  10734. transaction.onabort = function (event) {
  10735. try {
  10736. if (event.srcElement.error.name === "QuotaExceededError") {
  10737. _this.hasReachedQuota = true;
  10738. }
  10739. } catch (ex) {
  10740. }
  10741. callback(-1);
  10742. };
  10743. transaction.oncomplete = function (event) {
  10744. callback(_this.manifestVersionFound);
  10745. };
  10746. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10747. var addRequest = transaction.objectStore("versions").put(newVersion);
  10748. addRequest.onsuccess = function (event) {
  10749. };
  10750. addRequest.onerror = function (event) {
  10751. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10752. };
  10753. } catch (ex) {
  10754. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10755. callback(-1);
  10756. }
  10757. } else {
  10758. callback(-1);
  10759. }
  10760. };
  10761. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10762. var _this = this;
  10763. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10764. var saveAndLoadFile = function (event) {
  10765. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10766. };
  10767. this._checkVersionFromDB(completeUrl, function (version) {
  10768. if (version !== -1) {
  10769. if (!_this.mustUpdateRessources) {
  10770. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10771. } else {
  10772. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10773. }
  10774. } else {
  10775. errorCallback();
  10776. }
  10777. });
  10778. };
  10779. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10780. if (this.isSupported) {
  10781. var targetStore;
  10782. if (url.indexOf(".babylon") !== -1) {
  10783. targetStore = "scenes";
  10784. } else {
  10785. targetStore = "textures";
  10786. }
  10787. var file;
  10788. var transaction = this.db.transaction([targetStore]);
  10789. transaction.oncomplete = function (event) {
  10790. if (file) {
  10791. callback(file.data);
  10792. } else {
  10793. notInDBCallback();
  10794. }
  10795. };
  10796. transaction.onabort = function (event) {
  10797. notInDBCallback();
  10798. };
  10799. var getRequest = transaction.objectStore(targetStore).get(url);
  10800. getRequest.onsuccess = function (event) {
  10801. file = (event.target).result;
  10802. };
  10803. getRequest.onerror = function (event) {
  10804. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10805. notInDBCallback();
  10806. };
  10807. } else {
  10808. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10809. callback();
  10810. }
  10811. };
  10812. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10813. var _this = this;
  10814. if (this.isSupported) {
  10815. var targetStore;
  10816. if (url.indexOf(".babylon") !== -1) {
  10817. targetStore = "scenes";
  10818. } else {
  10819. targetStore = "textures";
  10820. }
  10821. var xhr = new XMLHttpRequest(), fileData;
  10822. xhr.open("GET", url, true);
  10823. if (useArrayBuffer) {
  10824. xhr.responseType = "arraybuffer";
  10825. }
  10826. xhr.onprogress = progressCallback;
  10827. xhr.addEventListener("load", function () {
  10828. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10829. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10830. if (!_this.hasReachedQuota) {
  10831. var transaction = _this.db.transaction([targetStore], "readwrite");
  10832. transaction.onabort = function (event) {
  10833. try {
  10834. if (event.srcElement.error.name === "QuotaExceededError") {
  10835. this.hasReachedQuota = true;
  10836. }
  10837. } catch (ex) {
  10838. }
  10839. callback(fileData);
  10840. };
  10841. transaction.oncomplete = function (event) {
  10842. callback(fileData);
  10843. };
  10844. var newFile;
  10845. if (targetStore === "scenes") {
  10846. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10847. } else {
  10848. newFile = { textureUrl: url, data: fileData };
  10849. }
  10850. try {
  10851. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10852. addRequest.onsuccess = function (event) {
  10853. };
  10854. addRequest.onerror = function (event) {
  10855. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10856. };
  10857. } catch (ex) {
  10858. callback(fileData);
  10859. }
  10860. } else {
  10861. callback(fileData);
  10862. }
  10863. } else {
  10864. callback();
  10865. }
  10866. }, false);
  10867. xhr.addEventListener("error", function (event) {
  10868. BABYLON.Tools.Error("error on XHR request.");
  10869. callback();
  10870. }, false);
  10871. xhr.send();
  10872. } else {
  10873. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10874. callback();
  10875. }
  10876. };
  10877. Database.isUASupportingBlobStorage = true;
  10878. Database.parseURL = function (url) {
  10879. var a = document.createElement('a');
  10880. a.href = url;
  10881. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10882. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10883. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10884. return absLocation;
  10885. };
  10886. Database.ReturnFullUrlLocation = function (url) {
  10887. if (url.indexOf("http:/") === -1) {
  10888. return (BABYLON.Database.parseURL(window.location.href) + url);
  10889. } else {
  10890. return url;
  10891. }
  10892. };
  10893. return Database;
  10894. })();
  10895. BABYLON.Database = Database;
  10896. })(BABYLON || (BABYLON = {}));
  10897. var BABYLON;
  10898. (function (BABYLON) {
  10899. var SpriteManager = (function () {
  10900. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10901. this.name = name;
  10902. this.cellSize = cellSize;
  10903. this.sprites = new Array();
  10904. this.renderingGroupId = 0;
  10905. this._vertexDeclaration = [3, 4, 4, 4];
  10906. this._vertexStrideSize = 15 * 4;
  10907. this._capacity = capacity;
  10908. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10909. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10910. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10911. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10912. this._scene = scene;
  10913. this._scene.spriteManagers.push(this);
  10914. this._vertexDeclaration = [3, 4, 4, 4];
  10915. this._vertexStrideSize = 15 * 4;
  10916. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10917. var indices = [];
  10918. var index = 0;
  10919. for (var count = 0; count < capacity; count++) {
  10920. indices.push(index);
  10921. indices.push(index + 1);
  10922. indices.push(index + 2);
  10923. indices.push(index);
  10924. indices.push(index + 2);
  10925. indices.push(index + 3);
  10926. index += 4;
  10927. }
  10928. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10929. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10930. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10931. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10932. }
  10933. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10934. var arrayOffset = index * 15;
  10935. if (offsetX == 0)
  10936. offsetX = this._epsilon;
  10937. else if (offsetX == 1)
  10938. offsetX = 1 - this._epsilon;
  10939. if (offsetY == 0)
  10940. offsetY = this._epsilon;
  10941. else if (offsetY == 1)
  10942. offsetY = 1 - this._epsilon;
  10943. this._vertices[arrayOffset] = sprite.position.x;
  10944. this._vertices[arrayOffset + 1] = sprite.position.y;
  10945. this._vertices[arrayOffset + 2] = sprite.position.z;
  10946. this._vertices[arrayOffset + 3] = sprite.angle;
  10947. this._vertices[arrayOffset + 4] = sprite.size;
  10948. this._vertices[arrayOffset + 5] = offsetX;
  10949. this._vertices[arrayOffset + 6] = offsetY;
  10950. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10951. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10952. var offset = (sprite.cellIndex / rowSize) >> 0;
  10953. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10954. this._vertices[arrayOffset + 10] = offset;
  10955. this._vertices[arrayOffset + 11] = sprite.color.r;
  10956. this._vertices[arrayOffset + 12] = sprite.color.g;
  10957. this._vertices[arrayOffset + 13] = sprite.color.b;
  10958. this._vertices[arrayOffset + 14] = sprite.color.a;
  10959. };
  10960. SpriteManager.prototype.render = function () {
  10961. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10962. return;
  10963. var engine = this._scene.getEngine();
  10964. var baseSize = this._spriteTexture.getBaseSize();
  10965. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10966. var max = Math.min(this._capacity, this.sprites.length);
  10967. var rowSize = baseSize.width / this.cellSize;
  10968. var offset = 0;
  10969. for (var index = 0; index < max; index++) {
  10970. var sprite = this.sprites[index];
  10971. if (!sprite) {
  10972. continue;
  10973. }
  10974. sprite._animate(deltaTime);
  10975. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  10976. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  10977. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  10978. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  10979. }
  10980. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  10981. var effect = this._effectBase;
  10982. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10983. effect = this._effectFog;
  10984. }
  10985. engine.enableEffect(effect);
  10986. var viewMatrix = this._scene.getViewMatrix();
  10987. effect.setTexture("diffuseSampler", this._spriteTexture);
  10988. effect.setMatrix("view", viewMatrix);
  10989. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  10990. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  10991. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10992. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  10993. effect.setColor3("vFogColor", this._scene.fogColor);
  10994. }
  10995. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  10996. effect.setBool("alphaTest", true);
  10997. engine.setColorWrite(false);
  10998. engine.draw(true, 0, max * 6);
  10999. engine.setColorWrite(true);
  11000. effect.setBool("alphaTest", false);
  11001. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11002. engine.draw(true, 0, max * 6);
  11003. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11004. };
  11005. SpriteManager.prototype.dispose = function () {
  11006. if (this._vertexBuffer) {
  11007. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11008. this._vertexBuffer = null;
  11009. }
  11010. if (this._indexBuffer) {
  11011. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11012. this._indexBuffer = null;
  11013. }
  11014. if (this._spriteTexture) {
  11015. this._spriteTexture.dispose();
  11016. this._spriteTexture = null;
  11017. }
  11018. var index = this._scene.spriteManagers.indexOf(this);
  11019. this._scene.spriteManagers.splice(index, 1);
  11020. if (this.onDispose) {
  11021. this.onDispose();
  11022. }
  11023. };
  11024. return SpriteManager;
  11025. })();
  11026. BABYLON.SpriteManager = SpriteManager;
  11027. })(BABYLON || (BABYLON = {}));
  11028. var BABYLON;
  11029. (function (BABYLON) {
  11030. var Sprite = (function () {
  11031. function Sprite(name, manager) {
  11032. this.name = name;
  11033. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11034. this.size = 1.0;
  11035. this.angle = 0;
  11036. this.cellIndex = 0;
  11037. this.invertU = 0;
  11038. this.invertV = 0;
  11039. this.animations = new Array();
  11040. this._animationStarted = false;
  11041. this._loopAnimation = false;
  11042. this._fromIndex = 0;
  11043. this._toIndex = 0;
  11044. this._delay = 0;
  11045. this._direction = 1;
  11046. this._frameCount = 0;
  11047. this._time = 0;
  11048. this._manager = manager;
  11049. this._manager.sprites.push(this);
  11050. this.position = BABYLON.Vector3.Zero();
  11051. }
  11052. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11053. this._fromIndex = from;
  11054. this._toIndex = to;
  11055. this._loopAnimation = loop;
  11056. this._delay = delay;
  11057. this._animationStarted = true;
  11058. this._direction = from < to ? 1 : -1;
  11059. this.cellIndex = from;
  11060. this._time = 0;
  11061. };
  11062. Sprite.prototype.stopAnimation = function () {
  11063. this._animationStarted = false;
  11064. };
  11065. Sprite.prototype._animate = function (deltaTime) {
  11066. if (!this._animationStarted)
  11067. return;
  11068. this._time += deltaTime;
  11069. if (this._time > this._delay) {
  11070. this._time = this._time % this._delay;
  11071. this.cellIndex += this._direction;
  11072. if (this.cellIndex == this._toIndex) {
  11073. if (this._loopAnimation) {
  11074. this.cellIndex = this._fromIndex;
  11075. } else {
  11076. this._animationStarted = false;
  11077. if (this.disposeWhenFinishedAnimating) {
  11078. this.dispose();
  11079. }
  11080. }
  11081. }
  11082. }
  11083. };
  11084. Sprite.prototype.dispose = function () {
  11085. for (var i = 0; i < this._manager.sprites.length; i++) {
  11086. if (this._manager.sprites[i] == this) {
  11087. this._manager.sprites.splice(i, 1);
  11088. }
  11089. }
  11090. };
  11091. return Sprite;
  11092. })();
  11093. BABYLON.Sprite = Sprite;
  11094. })(BABYLON || (BABYLON = {}));
  11095. var BABYLON;
  11096. (function (BABYLON) {
  11097. var Layer = (function () {
  11098. function Layer(name, imgUrl, scene, isBackground, color) {
  11099. this.name = name;
  11100. this._vertexDeclaration = [2];
  11101. this._vertexStrideSize = 2 * 4;
  11102. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11103. this.isBackground = isBackground === undefined ? true : isBackground;
  11104. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11105. this._scene = scene;
  11106. this._scene.layers.push(this);
  11107. var vertices = [];
  11108. vertices.push(1, 1);
  11109. vertices.push(-1, 1);
  11110. vertices.push(-1, -1);
  11111. vertices.push(1, -1);
  11112. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11113. var indices = [];
  11114. indices.push(0);
  11115. indices.push(1);
  11116. indices.push(2);
  11117. indices.push(0);
  11118. indices.push(2);
  11119. indices.push(3);
  11120. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11121. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11122. }
  11123. Layer.prototype.render = function () {
  11124. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11125. return;
  11126. var engine = this._scene.getEngine();
  11127. engine.enableEffect(this._effect);
  11128. engine.setState(false);
  11129. this._effect.setTexture("textureSampler", this.texture);
  11130. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11131. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11132. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11133. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11134. engine.draw(true, 0, 6);
  11135. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11136. };
  11137. Layer.prototype.dispose = function () {
  11138. if (this._vertexBuffer) {
  11139. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11140. this._vertexBuffer = null;
  11141. }
  11142. if (this._indexBuffer) {
  11143. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11144. this._indexBuffer = null;
  11145. }
  11146. if (this.texture) {
  11147. this.texture.dispose();
  11148. this.texture = null;
  11149. }
  11150. var index = this._scene.layers.indexOf(this);
  11151. this._scene.layers.splice(index, 1);
  11152. if (this.onDispose) {
  11153. this.onDispose();
  11154. }
  11155. };
  11156. return Layer;
  11157. })();
  11158. BABYLON.Layer = Layer;
  11159. })(BABYLON || (BABYLON = {}));
  11160. var BABYLON;
  11161. (function (BABYLON) {
  11162. var Particle = (function () {
  11163. function Particle() {
  11164. this.position = BABYLON.Vector3.Zero();
  11165. this.direction = BABYLON.Vector3.Zero();
  11166. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11167. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11168. this.lifeTime = 1.0;
  11169. this.age = 0;
  11170. this.size = 0;
  11171. this.angle = 0;
  11172. this.angularSpeed = 0;
  11173. }
  11174. return Particle;
  11175. })();
  11176. BABYLON.Particle = Particle;
  11177. })(BABYLON || (BABYLON = {}));
  11178. var BABYLON;
  11179. (function (BABYLON) {
  11180. var randomNumber = function (min, max) {
  11181. if (min == max) {
  11182. return (min);
  11183. }
  11184. var random = Math.random();
  11185. return ((random * (max - min)) + min);
  11186. };
  11187. var ParticleSystem = (function () {
  11188. function ParticleSystem(name, capacity, scene, fragmentElement) {
  11189. var _this = this;
  11190. this.name = name;
  11191. this.fragmentElement = fragmentElement;
  11192. this.renderingGroupId = 0;
  11193. this.emitter = null;
  11194. this.emitRate = 10;
  11195. this.manualEmitCount = -1;
  11196. this.updateSpeed = 0.01;
  11197. this.targetStopDuration = 0;
  11198. this.disposeOnStop = false;
  11199. this.minEmitPower = 1;
  11200. this.maxEmitPower = 1;
  11201. this.minLifeTime = 1;
  11202. this.maxLifeTime = 1;
  11203. this.minSize = 1;
  11204. this.maxSize = 1;
  11205. this.minAngularSpeed = 0;
  11206. this.maxAngularSpeed = 0;
  11207. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11208. this.forceDepthWrite = false;
  11209. this.gravity = BABYLON.Vector3.Zero();
  11210. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11211. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11212. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11213. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11214. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11215. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11216. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11217. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11218. this.particles = new Array();
  11219. this._vertexDeclaration = [3, 4, 4];
  11220. this._vertexStrideSize = 11 * 4;
  11221. this._stockParticles = new Array();
  11222. this._newPartsExcess = 0;
  11223. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11224. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11225. this._scaledDirection = BABYLON.Vector3.Zero();
  11226. this._scaledGravity = BABYLON.Vector3.Zero();
  11227. this._currentRenderId = -1;
  11228. this._started = false;
  11229. this._stopped = false;
  11230. this._actualFrame = 0;
  11231. this.id = name;
  11232. this._capacity = capacity;
  11233. this._scene = scene;
  11234. scene.particleSystems.push(this);
  11235. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11236. var indices = [];
  11237. var index = 0;
  11238. for (var count = 0; count < capacity; count++) {
  11239. indices.push(index);
  11240. indices.push(index + 1);
  11241. indices.push(index + 2);
  11242. indices.push(index);
  11243. indices.push(index + 2);
  11244. indices.push(index + 3);
  11245. index += 4;
  11246. }
  11247. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11248. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11249. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11250. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11251. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11252. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11253. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11254. };
  11255. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11256. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11257. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11258. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11259. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11260. };
  11261. }
  11262. ParticleSystem.prototype.getCapacity = function () {
  11263. return this._capacity;
  11264. };
  11265. ParticleSystem.prototype.isAlive = function () {
  11266. return this._alive;
  11267. };
  11268. ParticleSystem.prototype.isStarted = function () {
  11269. return this._started;
  11270. };
  11271. ParticleSystem.prototype.start = function () {
  11272. this._started = true;
  11273. this._stopped = false;
  11274. this._actualFrame = 0;
  11275. };
  11276. ParticleSystem.prototype.stop = function () {
  11277. this._stopped = true;
  11278. };
  11279. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11280. var offset = index * 11;
  11281. this._vertices[offset] = particle.position.x;
  11282. this._vertices[offset + 1] = particle.position.y;
  11283. this._vertices[offset + 2] = particle.position.z;
  11284. this._vertices[offset + 3] = particle.color.r;
  11285. this._vertices[offset + 4] = particle.color.g;
  11286. this._vertices[offset + 5] = particle.color.b;
  11287. this._vertices[offset + 6] = particle.color.a;
  11288. this._vertices[offset + 7] = particle.angle;
  11289. this._vertices[offset + 8] = particle.size;
  11290. this._vertices[offset + 9] = offsetX;
  11291. this._vertices[offset + 10] = offsetY;
  11292. };
  11293. ParticleSystem.prototype._update = function (newParticles) {
  11294. this._alive = this.particles.length > 0;
  11295. for (var index = 0; index < this.particles.length; index++) {
  11296. var particle = this.particles[index];
  11297. particle.age += this._scaledUpdateSpeed;
  11298. if (particle.age >= particle.lifeTime) {
  11299. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11300. index--;
  11301. continue;
  11302. } else {
  11303. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11304. particle.color.addInPlace(this._scaledColorStep);
  11305. if (particle.color.a < 0)
  11306. particle.color.a = 0;
  11307. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11308. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11309. particle.position.addInPlace(this._scaledDirection);
  11310. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11311. particle.direction.addInPlace(this._scaledGravity);
  11312. }
  11313. }
  11314. var worldMatrix;
  11315. if (this.emitter.position) {
  11316. worldMatrix = this.emitter.getWorldMatrix();
  11317. } else {
  11318. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11319. }
  11320. for (index = 0; index < newParticles; index++) {
  11321. if (this.particles.length == this._capacity) {
  11322. break;
  11323. }
  11324. if (this._stockParticles.length !== 0) {
  11325. particle = this._stockParticles.pop();
  11326. particle.age = 0;
  11327. } else {
  11328. particle = new BABYLON.Particle();
  11329. }
  11330. this.particles.push(particle);
  11331. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11332. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11333. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11334. particle.size = randomNumber(this.minSize, this.maxSize);
  11335. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11336. this.startPositionFunction(worldMatrix, particle.position);
  11337. var step = randomNumber(0, 1.0);
  11338. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11339. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11340. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11341. }
  11342. };
  11343. ParticleSystem.prototype._getEffect = function () {
  11344. var defines = [];
  11345. if (this._scene.clipPlane) {
  11346. defines.push("#define CLIPPLANE");
  11347. }
  11348. var join = defines.join("\n");
  11349. if (this._cachedDefines != join) {
  11350. this._cachedDefines = join;
  11351. var baseName;
  11352. if (this.fragmentElement) {
  11353. baseName = {
  11354. vertex: "particles",
  11355. fragmentElement: this.fragmentElement
  11356. };
  11357. } else {
  11358. baseName = "particles";
  11359. }
  11360. this._effect = this._scene.getEngine().createEffect(baseName, ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11361. }
  11362. return this._effect;
  11363. };
  11364. ParticleSystem.prototype.animate = function () {
  11365. if (!this._started)
  11366. return;
  11367. var effect = this._getEffect();
  11368. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11369. return;
  11370. if (this._currentRenderId === this._scene.getRenderId()) {
  11371. return;
  11372. }
  11373. this._currentRenderId = this._scene.getRenderId();
  11374. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11375. var emitCout;
  11376. if (this.manualEmitCount > -1) {
  11377. emitCout = this.manualEmitCount;
  11378. this.manualEmitCount = 0;
  11379. } else {
  11380. emitCout = this.emitRate;
  11381. }
  11382. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11383. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11384. if (this._newPartsExcess > 1.0) {
  11385. newParticles += this._newPartsExcess >> 0;
  11386. this._newPartsExcess -= this._newPartsExcess >> 0;
  11387. }
  11388. this._alive = false;
  11389. if (!this._stopped) {
  11390. this._actualFrame += this._scaledUpdateSpeed;
  11391. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11392. this.stop();
  11393. } else {
  11394. newParticles = 0;
  11395. }
  11396. this._update(newParticles);
  11397. if (this._stopped) {
  11398. if (!this._alive) {
  11399. this._started = false;
  11400. if (this.disposeOnStop) {
  11401. this._scene._toBeDisposed.push(this);
  11402. }
  11403. }
  11404. }
  11405. var offset = 0;
  11406. for (var index = 0; index < this.particles.length; index++) {
  11407. var particle = this.particles[index];
  11408. this._appendParticleVertex(offset++, particle, 0, 0);
  11409. this._appendParticleVertex(offset++, particle, 1, 0);
  11410. this._appendParticleVertex(offset++, particle, 1, 1);
  11411. this._appendParticleVertex(offset++, particle, 0, 1);
  11412. }
  11413. var engine = this._scene.getEngine();
  11414. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11415. };
  11416. ParticleSystem.prototype.render = function () {
  11417. var effect = this._getEffect();
  11418. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11419. return 0;
  11420. var engine = this._scene.getEngine();
  11421. engine.enableEffect(effect);
  11422. var viewMatrix = this._scene.getViewMatrix();
  11423. effect.setTexture("diffuseSampler", this.particleTexture);
  11424. effect.setMatrix("view", viewMatrix);
  11425. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11426. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11427. if (this._scene.clipPlane) {
  11428. var clipPlane = this._scene.clipPlane;
  11429. var invView = viewMatrix.clone();
  11430. invView.invert();
  11431. effect.setMatrix("invView", invView);
  11432. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11433. }
  11434. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11435. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11436. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11437. } else {
  11438. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11439. }
  11440. if (this.forceDepthWrite) {
  11441. engine.setDepthWrite(true);
  11442. }
  11443. engine.draw(true, 0, this.particles.length * 6);
  11444. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11445. return this.particles.length;
  11446. };
  11447. ParticleSystem.prototype.dispose = function () {
  11448. if (this._vertexBuffer) {
  11449. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11450. this._vertexBuffer = null;
  11451. }
  11452. if (this._indexBuffer) {
  11453. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11454. this._indexBuffer = null;
  11455. }
  11456. if (this.particleTexture) {
  11457. this.particleTexture.dispose();
  11458. this.particleTexture = null;
  11459. }
  11460. var index = this._scene.particleSystems.indexOf(this);
  11461. this._scene.particleSystems.splice(index, 1);
  11462. if (this.onDispose) {
  11463. this.onDispose();
  11464. }
  11465. };
  11466. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11467. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11468. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11469. if (newEmitter === undefined) {
  11470. newEmitter = this.emitter;
  11471. }
  11472. result.emitter = newEmitter;
  11473. if (this.particleTexture) {
  11474. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11475. }
  11476. result.start();
  11477. return result;
  11478. };
  11479. ParticleSystem.BLENDMODE_ONEONE = 0;
  11480. ParticleSystem.BLENDMODE_STANDARD = 1;
  11481. return ParticleSystem;
  11482. })();
  11483. BABYLON.ParticleSystem = ParticleSystem;
  11484. })(BABYLON || (BABYLON = {}));
  11485. var BABYLON;
  11486. (function (BABYLON) {
  11487. var Animation = (function () {
  11488. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11489. this.name = name;
  11490. this.targetProperty = targetProperty;
  11491. this.framePerSecond = framePerSecond;
  11492. this.dataType = dataType;
  11493. this.loopMode = loopMode;
  11494. this._offsetsCache = {};
  11495. this._highLimitsCache = {};
  11496. this._stopped = false;
  11497. this.targetPropertyPath = targetProperty.split(".");
  11498. this.dataType = dataType;
  11499. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11500. }
  11501. Animation.prototype.isStopped = function () {
  11502. return this._stopped;
  11503. };
  11504. Animation.prototype.getKeys = function () {
  11505. return this._keys;
  11506. };
  11507. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11508. return startValue + (endValue - startValue) * gradient;
  11509. };
  11510. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11511. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11512. };
  11513. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11514. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11515. };
  11516. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11517. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11518. };
  11519. Animation.prototype.clone = function () {
  11520. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11521. clone.setKeys(this._keys);
  11522. return clone;
  11523. };
  11524. Animation.prototype.setKeys = function (values) {
  11525. this._keys = values.slice(0);
  11526. this._offsetsCache = {};
  11527. this._highLimitsCache = {};
  11528. };
  11529. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11530. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11531. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11532. }
  11533. this.currentFrame = currentFrame;
  11534. for (var key = 0; key < this._keys.length; key++) {
  11535. if (this._keys[key + 1].frame >= currentFrame) {
  11536. var startValue = this._keys[key].value;
  11537. var endValue = this._keys[key + 1].value;
  11538. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11539. switch (this.dataType) {
  11540. case Animation.ANIMATIONTYPE_FLOAT:
  11541. switch (loopMode) {
  11542. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11543. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11544. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11545. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11546. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11547. }
  11548. break;
  11549. case Animation.ANIMATIONTYPE_QUATERNION:
  11550. var quaternion = null;
  11551. switch (loopMode) {
  11552. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11553. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11554. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11555. break;
  11556. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11557. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11558. break;
  11559. }
  11560. return quaternion;
  11561. case Animation.ANIMATIONTYPE_VECTOR3:
  11562. switch (loopMode) {
  11563. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11564. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11565. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11566. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11567. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11568. }
  11569. case Animation.ANIMATIONTYPE_COLOR3:
  11570. switch (loopMode) {
  11571. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11572. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11573. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11574. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11575. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11576. }
  11577. case Animation.ANIMATIONTYPE_MATRIX:
  11578. switch (loopMode) {
  11579. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11580. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11581. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11582. return startValue;
  11583. }
  11584. default:
  11585. break;
  11586. }
  11587. break;
  11588. }
  11589. }
  11590. return this._keys[this._keys.length - 1].value;
  11591. };
  11592. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11593. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11594. this._stopped = true;
  11595. return false;
  11596. }
  11597. var returnValue = true;
  11598. if (this._keys[0].frame != 0) {
  11599. var newKey = {
  11600. frame: 0,
  11601. value: this._keys[0].value
  11602. };
  11603. this._keys.splice(0, 0, newKey);
  11604. }
  11605. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11606. from = this._keys[0].frame;
  11607. }
  11608. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11609. to = this._keys[this._keys.length - 1].frame;
  11610. }
  11611. var range = to - from;
  11612. var offsetValue;
  11613. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11614. if (ratio > range && !loop) {
  11615. returnValue = false;
  11616. highLimitValue = this._keys[this._keys.length - 1].value;
  11617. } else {
  11618. var highLimitValue = 0;
  11619. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11620. var keyOffset = to.toString() + from.toString();
  11621. if (!this._offsetsCache[keyOffset]) {
  11622. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11623. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11624. switch (this.dataType) {
  11625. case Animation.ANIMATIONTYPE_FLOAT:
  11626. this._offsetsCache[keyOffset] = toValue - fromValue;
  11627. break;
  11628. case Animation.ANIMATIONTYPE_QUATERNION:
  11629. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11630. break;
  11631. case Animation.ANIMATIONTYPE_VECTOR3:
  11632. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11633. case Animation.ANIMATIONTYPE_COLOR3:
  11634. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11635. default:
  11636. break;
  11637. }
  11638. this._highLimitsCache[keyOffset] = toValue;
  11639. }
  11640. highLimitValue = this._highLimitsCache[keyOffset];
  11641. offsetValue = this._offsetsCache[keyOffset];
  11642. }
  11643. }
  11644. if (offsetValue === undefined) {
  11645. switch (this.dataType) {
  11646. case Animation.ANIMATIONTYPE_FLOAT:
  11647. offsetValue = 0;
  11648. break;
  11649. case Animation.ANIMATIONTYPE_QUATERNION:
  11650. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11651. break;
  11652. case Animation.ANIMATIONTYPE_VECTOR3:
  11653. offsetValue = BABYLON.Vector3.Zero();
  11654. break;
  11655. case Animation.ANIMATIONTYPE_COLOR3:
  11656. offsetValue = BABYLON.Color3.Black();
  11657. }
  11658. }
  11659. var repeatCount = (ratio / range) >> 0;
  11660. var currentFrame = returnValue ? from + ratio % range : to;
  11661. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11662. if (this.targetPropertyPath.length > 1) {
  11663. var property = this._target[this.targetPropertyPath[0]];
  11664. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11665. property = property[this.targetPropertyPath[index]];
  11666. }
  11667. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11668. } else {
  11669. this._target[this.targetPropertyPath[0]] = currentValue;
  11670. }
  11671. if (this._target.markAsDirty) {
  11672. this._target.markAsDirty(this.targetProperty);
  11673. }
  11674. if (!returnValue) {
  11675. this._stopped = true;
  11676. }
  11677. return returnValue;
  11678. };
  11679. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11680. get: function () {
  11681. return Animation._ANIMATIONTYPE_FLOAT;
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11687. get: function () {
  11688. return Animation._ANIMATIONTYPE_VECTOR3;
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11694. get: function () {
  11695. return Animation._ANIMATIONTYPE_QUATERNION;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11701. get: function () {
  11702. return Animation._ANIMATIONTYPE_MATRIX;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11708. get: function () {
  11709. return Animation._ANIMATIONTYPE_COLOR3;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11715. get: function () {
  11716. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11722. get: function () {
  11723. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11729. get: function () {
  11730. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Animation._ANIMATIONTYPE_FLOAT = 0;
  11736. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11737. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11738. Animation._ANIMATIONTYPE_MATRIX = 3;
  11739. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11740. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11741. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11742. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11743. return Animation;
  11744. })();
  11745. BABYLON.Animation = Animation;
  11746. })(BABYLON || (BABYLON = {}));
  11747. var BABYLON;
  11748. (function (BABYLON) {
  11749. var Animatable = (function () {
  11750. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11751. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11752. if (typeof toFrame === "undefined") { toFrame = 100; }
  11753. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11754. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11755. this.target = target;
  11756. this.fromFrame = fromFrame;
  11757. this.toFrame = toFrame;
  11758. this.loopAnimation = loopAnimation;
  11759. this.speedRatio = speedRatio;
  11760. this.onAnimationEnd = onAnimationEnd;
  11761. this._animations = new Array();
  11762. this._paused = false;
  11763. this.animationStarted = false;
  11764. if (animations) {
  11765. this.appendAnimations(target, animations);
  11766. }
  11767. this._scene = scene;
  11768. scene._activeAnimatables.push(this);
  11769. }
  11770. Animatable.prototype.appendAnimations = function (target, animations) {
  11771. for (var index = 0; index < animations.length; index++) {
  11772. var animation = animations[index];
  11773. animation._target = target;
  11774. this._animations.push(animation);
  11775. }
  11776. };
  11777. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11778. var animations = this._animations;
  11779. for (var index = 0; index < animations.length; index++) {
  11780. if (animations[index].targetProperty === property) {
  11781. return animations[index];
  11782. }
  11783. }
  11784. return null;
  11785. };
  11786. Animatable.prototype.pause = function () {
  11787. this._paused = true;
  11788. };
  11789. Animatable.prototype.restart = function () {
  11790. this._paused = false;
  11791. };
  11792. Animatable.prototype.stop = function () {
  11793. var index = this._scene._activeAnimatables.indexOf(this);
  11794. if (index > -1) {
  11795. this._scene._activeAnimatables.splice(index, 1);
  11796. }
  11797. if (this.onAnimationEnd) {
  11798. this.onAnimationEnd();
  11799. }
  11800. };
  11801. Animatable.prototype._animate = function (delay) {
  11802. if (this._paused) {
  11803. return true;
  11804. }
  11805. if (!this._localDelayOffset) {
  11806. this._localDelayOffset = delay;
  11807. }
  11808. var running = false;
  11809. var animations = this._animations;
  11810. for (var index = 0; index < animations.length; index++) {
  11811. var animation = animations[index];
  11812. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11813. running = running || isRunning;
  11814. }
  11815. if (!running && this.onAnimationEnd) {
  11816. this.onAnimationEnd();
  11817. }
  11818. return running;
  11819. };
  11820. return Animatable;
  11821. })();
  11822. BABYLON.Animatable = Animatable;
  11823. })(BABYLON || (BABYLON = {}));
  11824. var BABYLON;
  11825. (function (BABYLON) {
  11826. var Octree = (function () {
  11827. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11828. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11829. this.maxDepth = maxDepth;
  11830. this.dynamicContent = new Array();
  11831. this._maxBlockCapacity = maxBlockCapacity || 64;
  11832. this._selectionContent = new BABYLON.SmartArray(1024);
  11833. this._creationFunc = creationFunc;
  11834. }
  11835. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11836. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11837. };
  11838. Octree.prototype.addMesh = function (entry) {
  11839. for (var index = 0; index < this.blocks.length; index++) {
  11840. var block = this.blocks[index];
  11841. block.addEntry(entry);
  11842. }
  11843. };
  11844. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11845. this._selectionContent.reset();
  11846. for (var index = 0; index < this.blocks.length; index++) {
  11847. var block = this.blocks[index];
  11848. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11849. }
  11850. if (allowDuplicate) {
  11851. this._selectionContent.concat(this.dynamicContent);
  11852. } else {
  11853. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11854. }
  11855. return this._selectionContent;
  11856. };
  11857. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11858. this._selectionContent.reset();
  11859. for (var index = 0; index < this.blocks.length; index++) {
  11860. var block = this.blocks[index];
  11861. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11862. }
  11863. if (allowDuplicate) {
  11864. this._selectionContent.concat(this.dynamicContent);
  11865. } else {
  11866. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11867. }
  11868. return this._selectionContent;
  11869. };
  11870. Octree.prototype.intersectsRay = function (ray) {
  11871. this._selectionContent.reset();
  11872. for (var index = 0; index < this.blocks.length; index++) {
  11873. var block = this.blocks[index];
  11874. block.intersectsRay(ray, this._selectionContent);
  11875. }
  11876. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11877. return this._selectionContent;
  11878. };
  11879. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11880. target.blocks = new Array();
  11881. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11882. for (var x = 0; x < 2; x++) {
  11883. for (var y = 0; y < 2; y++) {
  11884. for (var z = 0; z < 2; z++) {
  11885. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11886. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11887. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11888. block.addEntries(entries);
  11889. target.blocks.push(block);
  11890. }
  11891. }
  11892. }
  11893. };
  11894. Octree.CreationFuncForMeshes = function (entry, block) {
  11895. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11896. block.entries.push(entry);
  11897. }
  11898. };
  11899. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11900. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11901. block.entries.push(entry);
  11902. }
  11903. };
  11904. return Octree;
  11905. })();
  11906. BABYLON.Octree = Octree;
  11907. })(BABYLON || (BABYLON = {}));
  11908. var BABYLON;
  11909. (function (BABYLON) {
  11910. var OctreeBlock = (function () {
  11911. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11912. this.entries = new Array();
  11913. this._boundingVectors = new Array();
  11914. this._capacity = capacity;
  11915. this._depth = depth;
  11916. this._maxDepth = maxDepth;
  11917. this._creationFunc = creationFunc;
  11918. this._minPoint = minPoint;
  11919. this._maxPoint = maxPoint;
  11920. this._boundingVectors.push(minPoint.clone());
  11921. this._boundingVectors.push(maxPoint.clone());
  11922. this._boundingVectors.push(minPoint.clone());
  11923. this._boundingVectors[2].x = maxPoint.x;
  11924. this._boundingVectors.push(minPoint.clone());
  11925. this._boundingVectors[3].y = maxPoint.y;
  11926. this._boundingVectors.push(minPoint.clone());
  11927. this._boundingVectors[4].z = maxPoint.z;
  11928. this._boundingVectors.push(maxPoint.clone());
  11929. this._boundingVectors[5].z = minPoint.z;
  11930. this._boundingVectors.push(maxPoint.clone());
  11931. this._boundingVectors[6].x = minPoint.x;
  11932. this._boundingVectors.push(maxPoint.clone());
  11933. this._boundingVectors[7].y = minPoint.y;
  11934. }
  11935. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11936. get: function () {
  11937. return this._capacity;
  11938. },
  11939. enumerable: true,
  11940. configurable: true
  11941. });
  11942. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11943. get: function () {
  11944. return this._minPoint;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11950. get: function () {
  11951. return this._maxPoint;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. OctreeBlock.prototype.addEntry = function (entry) {
  11957. if (this.blocks) {
  11958. for (var index = 0; index < this.blocks.length; index++) {
  11959. var block = this.blocks[index];
  11960. block.addEntry(entry);
  11961. }
  11962. return;
  11963. }
  11964. this._creationFunc(entry, this);
  11965. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11966. this.createInnerBlocks();
  11967. }
  11968. };
  11969. OctreeBlock.prototype.addEntries = function (entries) {
  11970. for (var index = 0; index < entries.length; index++) {
  11971. var mesh = entries[index];
  11972. this.addEntry(mesh);
  11973. }
  11974. };
  11975. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11976. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11977. if (this.blocks) {
  11978. for (var index = 0; index < this.blocks.length; index++) {
  11979. var block = this.blocks[index];
  11980. block.select(frustumPlanes, selection, allowDuplicate);
  11981. }
  11982. return;
  11983. }
  11984. if (allowDuplicate) {
  11985. selection.concat(this.entries);
  11986. } else {
  11987. selection.concatWithNoDuplicate(this.entries);
  11988. }
  11989. }
  11990. };
  11991. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  11992. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  11993. if (this.blocks) {
  11994. for (var index = 0; index < this.blocks.length; index++) {
  11995. var block = this.blocks[index];
  11996. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  11997. }
  11998. return;
  11999. }
  12000. if (allowDuplicate) {
  12001. selection.concat(this.entries);
  12002. } else {
  12003. selection.concatWithNoDuplicate(this.entries);
  12004. }
  12005. }
  12006. };
  12007. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12008. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12009. if (this.blocks) {
  12010. for (var index = 0; index < this.blocks.length; index++) {
  12011. var block = this.blocks[index];
  12012. block.intersectsRay(ray, selection);
  12013. }
  12014. return;
  12015. }
  12016. selection.concatWithNoDuplicate(this.entries);
  12017. }
  12018. };
  12019. OctreeBlock.prototype.createInnerBlocks = function () {
  12020. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12021. };
  12022. return OctreeBlock;
  12023. })();
  12024. BABYLON.OctreeBlock = OctreeBlock;
  12025. })(BABYLON || (BABYLON = {}));
  12026. var BABYLON;
  12027. (function (BABYLON) {
  12028. var Bone = (function () {
  12029. function Bone(name, skeleton, parentBone, matrix) {
  12030. this.name = name;
  12031. this.children = new Array();
  12032. this.animations = new Array();
  12033. this._worldTransform = new BABYLON.Matrix();
  12034. this._absoluteTransform = new BABYLON.Matrix();
  12035. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12036. this._skeleton = skeleton;
  12037. this._matrix = matrix;
  12038. this._baseMatrix = matrix;
  12039. skeleton.bones.push(this);
  12040. if (parentBone) {
  12041. this._parent = parentBone;
  12042. parentBone.children.push(this);
  12043. } else {
  12044. this._parent = null;
  12045. }
  12046. this._updateDifferenceMatrix();
  12047. }
  12048. Bone.prototype.getParent = function () {
  12049. return this._parent;
  12050. };
  12051. Bone.prototype.getLocalMatrix = function () {
  12052. return this._matrix;
  12053. };
  12054. Bone.prototype.getBaseMatrix = function () {
  12055. return this._baseMatrix;
  12056. };
  12057. Bone.prototype.getWorldMatrix = function () {
  12058. return this._worldTransform;
  12059. };
  12060. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12061. return this._invertedAbsoluteTransform;
  12062. };
  12063. Bone.prototype.getAbsoluteMatrix = function () {
  12064. var matrix = this._matrix.clone();
  12065. var parent = this._parent;
  12066. while (parent) {
  12067. matrix = matrix.multiply(parent.getLocalMatrix());
  12068. parent = parent.getParent();
  12069. }
  12070. return matrix;
  12071. };
  12072. Bone.prototype.updateMatrix = function (matrix) {
  12073. this._matrix = matrix;
  12074. this._skeleton._markAsDirty();
  12075. this._updateDifferenceMatrix();
  12076. };
  12077. Bone.prototype._updateDifferenceMatrix = function () {
  12078. if (this._parent) {
  12079. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12080. } else {
  12081. this._absoluteTransform.copyFrom(this._matrix);
  12082. }
  12083. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12084. for (var index = 0; index < this.children.length; index++) {
  12085. this.children[index]._updateDifferenceMatrix();
  12086. }
  12087. };
  12088. Bone.prototype.markAsDirty = function () {
  12089. this._skeleton._markAsDirty();
  12090. };
  12091. return Bone;
  12092. })();
  12093. BABYLON.Bone = Bone;
  12094. })(BABYLON || (BABYLON = {}));
  12095. var BABYLON;
  12096. (function (BABYLON) {
  12097. var Skeleton = (function () {
  12098. function Skeleton(name, id, scene) {
  12099. this.name = name;
  12100. this.id = id;
  12101. this.bones = new Array();
  12102. this._isDirty = true;
  12103. this._identity = BABYLON.Matrix.Identity();
  12104. this.bones = [];
  12105. this._scene = scene;
  12106. scene.skeletons.push(this);
  12107. }
  12108. Skeleton.prototype.getTransformMatrices = function () {
  12109. return this._transformMatrices;
  12110. };
  12111. Skeleton.prototype._markAsDirty = function () {
  12112. this._isDirty = true;
  12113. };
  12114. Skeleton.prototype.prepare = function () {
  12115. if (!this._isDirty) {
  12116. return;
  12117. }
  12118. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12119. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12120. }
  12121. for (var index = 0; index < this.bones.length; index++) {
  12122. var bone = this.bones[index];
  12123. var parentBone = bone.getParent();
  12124. if (parentBone) {
  12125. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12126. } else {
  12127. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12128. }
  12129. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12130. }
  12131. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12132. this._isDirty = false;
  12133. };
  12134. Skeleton.prototype.getAnimatables = function () {
  12135. if (!this._animatables || this._animatables.length != this.bones.length) {
  12136. this._animatables = [];
  12137. for (var index = 0; index < this.bones.length; index++) {
  12138. this._animatables.push(this.bones[index]);
  12139. }
  12140. }
  12141. return this._animatables;
  12142. };
  12143. Skeleton.prototype.clone = function (name, id) {
  12144. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12145. for (var index = 0; index < this.bones.length; index++) {
  12146. var source = this.bones[index];
  12147. var parentBone = null;
  12148. if (source.getParent()) {
  12149. var parentIndex = this.bones.indexOf(source.getParent());
  12150. parentBone = result.bones[parentIndex];
  12151. }
  12152. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12153. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12154. }
  12155. return result;
  12156. };
  12157. return Skeleton;
  12158. })();
  12159. BABYLON.Skeleton = Skeleton;
  12160. })(BABYLON || (BABYLON = {}));
  12161. var BABYLON;
  12162. (function (BABYLON) {
  12163. var PostProcess = (function () {
  12164. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12165. this.name = name;
  12166. this.width = -1;
  12167. this.height = -1;
  12168. this._reusable = false;
  12169. this._textures = new BABYLON.SmartArray(2);
  12170. this._currentRenderTextureInd = 0;
  12171. if (camera != null) {
  12172. this._camera = camera;
  12173. this._scene = camera.getScene();
  12174. camera.attachPostProcess(this);
  12175. this._engine = this._scene.getEngine();
  12176. } else {
  12177. this._engine = engine;
  12178. }
  12179. this._renderRatio = ratio;
  12180. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12181. this._reusable = reusable || false;
  12182. samplers = samplers || [];
  12183. samplers.push("textureSampler");
  12184. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12185. }
  12186. PostProcess.prototype.isReusable = function () {
  12187. return this._reusable;
  12188. };
  12189. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12190. camera = camera || this._camera;
  12191. var scene = camera.getScene();
  12192. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12193. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12194. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12195. if (this._textures.length > 0) {
  12196. for (var i = 0; i < this._textures.length; i++) {
  12197. this._engine._releaseTexture(this._textures.data[i]);
  12198. }
  12199. this._textures.reset();
  12200. }
  12201. this.width = desiredWidth;
  12202. this.height = desiredHeight;
  12203. 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 }));
  12204. if (this._reusable) {
  12205. 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 }));
  12206. }
  12207. if (this.onSizeChanged) {
  12208. this.onSizeChanged();
  12209. }
  12210. }
  12211. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12212. if (this.onActivate) {
  12213. this.onActivate(camera);
  12214. }
  12215. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12216. if (this._reusable) {
  12217. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12218. }
  12219. };
  12220. PostProcess.prototype.apply = function () {
  12221. if (!this._effect.isReady())
  12222. return null;
  12223. this._engine.enableEffect(this._effect);
  12224. this._engine.setState(false);
  12225. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12226. this._engine.setDepthBuffer(false);
  12227. this._engine.setDepthWrite(false);
  12228. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12229. if (this.onApply) {
  12230. this.onApply(this._effect);
  12231. }
  12232. return this._effect;
  12233. };
  12234. PostProcess.prototype.dispose = function (camera) {
  12235. camera = camera || this._camera;
  12236. if (this._textures.length > 0) {
  12237. for (var i = 0; i < this._textures.length; i++) {
  12238. this._engine._releaseTexture(this._textures.data[i]);
  12239. }
  12240. this._textures.reset();
  12241. }
  12242. camera.detachPostProcess(this);
  12243. var index = camera._postProcesses.indexOf(this);
  12244. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12245. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12246. }
  12247. };
  12248. return PostProcess;
  12249. })();
  12250. BABYLON.PostProcess = PostProcess;
  12251. })(BABYLON || (BABYLON = {}));
  12252. var BABYLON;
  12253. (function (BABYLON) {
  12254. var PostProcessManager = (function () {
  12255. function PostProcessManager(scene) {
  12256. this._vertexDeclaration = [2];
  12257. this._vertexStrideSize = 2 * 4;
  12258. this._scene = scene;
  12259. var vertices = [];
  12260. vertices.push(1, 1);
  12261. vertices.push(-1, 1);
  12262. vertices.push(-1, -1);
  12263. vertices.push(1, -1);
  12264. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12265. var indices = [];
  12266. indices.push(0);
  12267. indices.push(1);
  12268. indices.push(2);
  12269. indices.push(0);
  12270. indices.push(2);
  12271. indices.push(3);
  12272. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12273. }
  12274. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12275. var postProcesses = this._scene.activeCamera._postProcesses;
  12276. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12277. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12278. return false;
  12279. }
  12280. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12281. return true;
  12282. };
  12283. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12284. var postProcesses = this._scene.activeCamera._postProcesses;
  12285. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12286. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12287. return;
  12288. }
  12289. var engine = this._scene.getEngine();
  12290. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12291. if (index < postProcessesTakenIndices.length - 1) {
  12292. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12293. } else {
  12294. if (targetTexture) {
  12295. engine.bindFramebuffer(targetTexture);
  12296. } else {
  12297. engine.restoreDefaultFramebuffer();
  12298. }
  12299. }
  12300. if (doNotPresent) {
  12301. break;
  12302. }
  12303. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12304. if (effect) {
  12305. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12306. engine.draw(true, 0, 6);
  12307. }
  12308. }
  12309. engine.setDepthBuffer(true);
  12310. engine.setDepthWrite(true);
  12311. };
  12312. PostProcessManager.prototype.dispose = function () {
  12313. if (this._vertexBuffer) {
  12314. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12315. this._vertexBuffer = null;
  12316. }
  12317. if (this._indexBuffer) {
  12318. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12319. this._indexBuffer = null;
  12320. }
  12321. };
  12322. return PostProcessManager;
  12323. })();
  12324. BABYLON.PostProcessManager = PostProcessManager;
  12325. })(BABYLON || (BABYLON = {}));
  12326. var __extends = this.__extends || function (d, b) {
  12327. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12328. function __() { this.constructor = d; }
  12329. __.prototype = b.prototype;
  12330. d.prototype = new __();
  12331. };
  12332. var BABYLON;
  12333. (function (BABYLON) {
  12334. var PassPostProcess = (function (_super) {
  12335. __extends(PassPostProcess, _super);
  12336. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12337. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12338. }
  12339. return PassPostProcess;
  12340. })(BABYLON.PostProcess);
  12341. BABYLON.PassPostProcess = PassPostProcess;
  12342. })(BABYLON || (BABYLON = {}));
  12343. var __extends = this.__extends || function (d, b) {
  12344. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12345. function __() { this.constructor = d; }
  12346. __.prototype = b.prototype;
  12347. d.prototype = new __();
  12348. };
  12349. var BABYLON;
  12350. (function (BABYLON) {
  12351. var BlurPostProcess = (function (_super) {
  12352. __extends(BlurPostProcess, _super);
  12353. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12354. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12355. var _this = this;
  12356. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12357. this.direction = direction;
  12358. this.blurWidth = blurWidth;
  12359. this.onApply = function (effect) {
  12360. effect.setFloat2("screenSize", _this.width, _this.height);
  12361. effect.setVector2("direction", _this.direction);
  12362. effect.setFloat("blurWidth", _this.blurWidth);
  12363. };
  12364. }
  12365. return BlurPostProcess;
  12366. })(BABYLON.PostProcess);
  12367. BABYLON.BlurPostProcess = BlurPostProcess;
  12368. })(BABYLON || (BABYLON = {}));
  12369. var __extends = this.__extends || function (d, b) {
  12370. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12371. function __() { this.constructor = d; }
  12372. __.prototype = b.prototype;
  12373. d.prototype = new __();
  12374. };
  12375. var BABYLON;
  12376. (function (BABYLON) {
  12377. var FilterPostProcess = (function (_super) {
  12378. __extends(FilterPostProcess, _super);
  12379. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12380. var _this = this;
  12381. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12382. this.kernelMatrix = kernelMatrix;
  12383. this.onApply = function (effect) {
  12384. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12385. };
  12386. }
  12387. return FilterPostProcess;
  12388. })(BABYLON.PostProcess);
  12389. BABYLON.FilterPostProcess = FilterPostProcess;
  12390. })(BABYLON || (BABYLON = {}));
  12391. var __extends = this.__extends || function (d, b) {
  12392. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12393. function __() { this.constructor = d; }
  12394. __.prototype = b.prototype;
  12395. d.prototype = new __();
  12396. };
  12397. var BABYLON;
  12398. (function (BABYLON) {
  12399. var RefractionPostProcess = (function (_super) {
  12400. __extends(RefractionPostProcess, _super);
  12401. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12402. var _this = this;
  12403. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12404. this.color = color;
  12405. this.depth = depth;
  12406. this.colorLevel = colorLevel;
  12407. this.onActivate = function (cam) {
  12408. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12409. };
  12410. this.onApply = function (effect) {
  12411. effect.setColor3("baseColor", _this.color);
  12412. effect.setFloat("depth", _this.depth);
  12413. effect.setFloat("colorLevel", _this.colorLevel);
  12414. effect.setTexture("refractionSampler", _this._refRexture);
  12415. };
  12416. }
  12417. RefractionPostProcess.prototype.dispose = function (camera) {
  12418. if (this._refRexture) {
  12419. this._refRexture.dispose();
  12420. }
  12421. _super.prototype.dispose.call(this, camera);
  12422. };
  12423. return RefractionPostProcess;
  12424. })(BABYLON.PostProcess);
  12425. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12426. })(BABYLON || (BABYLON = {}));
  12427. var __extends = this.__extends || function (d, b) {
  12428. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12429. function __() { this.constructor = d; }
  12430. __.prototype = b.prototype;
  12431. d.prototype = new __();
  12432. };
  12433. var BABYLON;
  12434. (function (BABYLON) {
  12435. var BlackAndWhitePostProcess = (function (_super) {
  12436. __extends(BlackAndWhitePostProcess, _super);
  12437. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12438. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12439. }
  12440. return BlackAndWhitePostProcess;
  12441. })(BABYLON.PostProcess);
  12442. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12443. })(BABYLON || (BABYLON = {}));
  12444. var __extends = this.__extends || function (d, b) {
  12445. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12446. function __() { this.constructor = d; }
  12447. __.prototype = b.prototype;
  12448. d.prototype = new __();
  12449. };
  12450. var BABYLON;
  12451. (function (BABYLON) {
  12452. var ConvolutionPostProcess = (function (_super) {
  12453. __extends(ConvolutionPostProcess, _super);
  12454. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12455. var _this = this;
  12456. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12457. this.kernel = kernel;
  12458. this.onApply = function (effect) {
  12459. effect.setFloat2("screenSize", _this.width, _this.height);
  12460. effect.setArray("kernel", _this.kernel);
  12461. };
  12462. }
  12463. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12464. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12465. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12466. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12467. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12468. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12469. return ConvolutionPostProcess;
  12470. })(BABYLON.PostProcess);
  12471. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12472. })(BABYLON || (BABYLON = {}));
  12473. var __extends = this.__extends || function (d, b) {
  12474. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12475. function __() { this.constructor = d; }
  12476. __.prototype = b.prototype;
  12477. d.prototype = new __();
  12478. };
  12479. var BABYLON;
  12480. (function (BABYLON) {
  12481. var FxaaPostProcess = (function (_super) {
  12482. __extends(FxaaPostProcess, _super);
  12483. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12484. var _this = this;
  12485. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12486. this.onSizeChanged = function () {
  12487. _this.texelWidth = 1.0 / _this.width;
  12488. _this.texelHeight = 1.0 / _this.height;
  12489. };
  12490. this.onApply = function (effect) {
  12491. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12492. };
  12493. }
  12494. return FxaaPostProcess;
  12495. })(BABYLON.PostProcess);
  12496. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12497. })(BABYLON || (BABYLON = {}));
  12498. var BABYLON;
  12499. (function (BABYLON) {
  12500. var LensFlare = (function () {
  12501. function LensFlare(size, position, color, imgUrl, system) {
  12502. this.size = size;
  12503. this.position = position;
  12504. this.dispose = function () {
  12505. if (this.texture) {
  12506. this.texture.dispose();
  12507. }
  12508. var index = this._system.lensFlares.indexOf(this);
  12509. this._system.lensFlares.splice(index, 1);
  12510. };
  12511. this.color = color || new BABYLON.Color3(1, 1, 1);
  12512. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12513. this._system = system;
  12514. system.lensFlares.push(this);
  12515. }
  12516. return LensFlare;
  12517. })();
  12518. BABYLON.LensFlare = LensFlare;
  12519. })(BABYLON || (BABYLON = {}));
  12520. var BABYLON;
  12521. (function (BABYLON) {
  12522. var LensFlareSystem = (function () {
  12523. function LensFlareSystem(name, emitter, scene) {
  12524. this.name = name;
  12525. this.lensFlares = new Array();
  12526. this.borderLimit = 300;
  12527. this._vertexDeclaration = [2];
  12528. this._vertexStrideSize = 2 * 4;
  12529. this._isEnabled = true;
  12530. this._scene = scene;
  12531. this._emitter = emitter;
  12532. scene.lensFlareSystems.push(this);
  12533. this.meshesSelectionPredicate = function (m) {
  12534. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12535. };
  12536. var vertices = [];
  12537. vertices.push(1, 1);
  12538. vertices.push(-1, 1);
  12539. vertices.push(-1, -1);
  12540. vertices.push(1, -1);
  12541. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12542. var indices = [];
  12543. indices.push(0);
  12544. indices.push(1);
  12545. indices.push(2);
  12546. indices.push(0);
  12547. indices.push(2);
  12548. indices.push(3);
  12549. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12550. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12551. }
  12552. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12553. get: function () {
  12554. return this._isEnabled;
  12555. },
  12556. set: function (value) {
  12557. this._isEnabled = value;
  12558. },
  12559. enumerable: true,
  12560. configurable: true
  12561. });
  12562. LensFlareSystem.prototype.getScene = function () {
  12563. return this._scene;
  12564. };
  12565. LensFlareSystem.prototype.getEmitter = function () {
  12566. return this._emitter;
  12567. };
  12568. LensFlareSystem.prototype.getEmitterPosition = function () {
  12569. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12570. };
  12571. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12572. var position = this.getEmitterPosition();
  12573. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12574. this._positionX = position.x;
  12575. this._positionY = position.y;
  12576. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12577. if (position.z > 0) {
  12578. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12579. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12580. return true;
  12581. }
  12582. }
  12583. return false;
  12584. };
  12585. LensFlareSystem.prototype._isVisible = function () {
  12586. if (!this._isEnabled) {
  12587. return false;
  12588. }
  12589. var emitterPosition = this.getEmitterPosition();
  12590. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12591. var distance = direction.length();
  12592. direction.normalize();
  12593. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12594. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12595. return !pickInfo.hit || pickInfo.distance > distance;
  12596. };
  12597. LensFlareSystem.prototype.render = function () {
  12598. if (!this._effect.isReady())
  12599. return false;
  12600. var engine = this._scene.getEngine();
  12601. var viewport = this._scene.activeCamera.viewport;
  12602. var globalViewport = viewport.toGlobal(engine);
  12603. if (!this.computeEffectivePosition(globalViewport)) {
  12604. return false;
  12605. }
  12606. if (!this._isVisible()) {
  12607. return false;
  12608. }
  12609. var awayX;
  12610. var awayY;
  12611. if (this._positionX < this.borderLimit + globalViewport.x) {
  12612. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12613. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12614. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12615. } else {
  12616. awayX = 0;
  12617. }
  12618. if (this._positionY < this.borderLimit + globalViewport.y) {
  12619. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12620. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12621. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12622. } else {
  12623. awayY = 0;
  12624. }
  12625. var away = (awayX > awayY) ? awayX : awayY;
  12626. if (away > this.borderLimit) {
  12627. away = this.borderLimit;
  12628. }
  12629. var intensity = 1.0 - (away / this.borderLimit);
  12630. if (intensity < 0) {
  12631. return false;
  12632. }
  12633. if (intensity > 1.0) {
  12634. intensity = 1.0;
  12635. }
  12636. var centerX = globalViewport.x + globalViewport.width / 2;
  12637. var centerY = globalViewport.y + globalViewport.height / 2;
  12638. var distX = centerX - this._positionX;
  12639. var distY = centerY - this._positionY;
  12640. engine.enableEffect(this._effect);
  12641. engine.setState(false);
  12642. engine.setDepthBuffer(false);
  12643. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12644. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12645. for (var index = 0; index < this.lensFlares.length; index++) {
  12646. var flare = this.lensFlares[index];
  12647. var x = centerX - (distX * flare.position);
  12648. var y = centerY - (distY * flare.position);
  12649. var cw = flare.size;
  12650. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12651. var cx = 2 * (x / globalViewport.width) - 1.0;
  12652. var cy = 1.0 - 2 * (y / globalViewport.height);
  12653. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12654. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12655. this._effect.setTexture("textureSampler", flare.texture);
  12656. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12657. engine.draw(true, 0, 6);
  12658. }
  12659. engine.setDepthBuffer(true);
  12660. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12661. return true;
  12662. };
  12663. LensFlareSystem.prototype.dispose = function () {
  12664. if (this._vertexBuffer) {
  12665. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12666. this._vertexBuffer = null;
  12667. }
  12668. if (this._indexBuffer) {
  12669. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12670. this._indexBuffer = null;
  12671. }
  12672. while (this.lensFlares.length) {
  12673. this.lensFlares[0].dispose();
  12674. }
  12675. var index = this._scene.lensFlareSystems.indexOf(this);
  12676. this._scene.lensFlareSystems.splice(index, 1);
  12677. };
  12678. return LensFlareSystem;
  12679. })();
  12680. BABYLON.LensFlareSystem = LensFlareSystem;
  12681. })(BABYLON || (BABYLON = {}));
  12682. var BABYLON;
  12683. (function (BABYLON) {
  12684. var IntersectionInfo = (function () {
  12685. function IntersectionInfo(bu, bv, distance) {
  12686. this.bu = bu;
  12687. this.bv = bv;
  12688. this.distance = distance;
  12689. this.faceId = 0;
  12690. }
  12691. return IntersectionInfo;
  12692. })();
  12693. BABYLON.IntersectionInfo = IntersectionInfo;
  12694. var PickingInfo = (function () {
  12695. function PickingInfo() {
  12696. this.hit = false;
  12697. this.distance = 0;
  12698. this.pickedPoint = null;
  12699. this.pickedMesh = null;
  12700. this.bu = 0;
  12701. this.bv = 0;
  12702. this.faceId = -1;
  12703. }
  12704. PickingInfo.prototype.getNormal = function () {
  12705. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12706. return null;
  12707. }
  12708. var indices = this.pickedMesh.getIndices();
  12709. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12710. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12711. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12712. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12713. normal0 = normal0.scale(this.bu);
  12714. normal1 = normal1.scale(this.bv);
  12715. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12716. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12717. };
  12718. PickingInfo.prototype.getTextureCoordinates = function () {
  12719. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12720. return null;
  12721. }
  12722. var indices = this.pickedMesh.getIndices();
  12723. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12724. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12725. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12726. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12727. uv0 = uv0.scale(this.bu);
  12728. uv1 = uv1.scale(this.bv);
  12729. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12730. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12731. };
  12732. return PickingInfo;
  12733. })();
  12734. BABYLON.PickingInfo = PickingInfo;
  12735. })(BABYLON || (BABYLON = {}));
  12736. var BABYLON;
  12737. (function (BABYLON) {
  12738. var FilesInput = (function () {
  12739. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12740. this.engine = p_engine;
  12741. this.canvas = p_canvas;
  12742. this.currentScene = p_scene;
  12743. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12744. this.progressCallback = p_progressCallback;
  12745. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12746. this.textureLoadingCallback = p_textureLoadingCallback;
  12747. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12748. }
  12749. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12750. var _this = this;
  12751. if (p_elementToMonitor) {
  12752. this.elementToMonitor = p_elementToMonitor;
  12753. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12754. _this.drag(e);
  12755. }, false);
  12756. this.elementToMonitor.addEventListener("dragover", function (e) {
  12757. _this.drag(e);
  12758. }, false);
  12759. this.elementToMonitor.addEventListener("drop", function (e) {
  12760. _this.drop(e);
  12761. }, false);
  12762. }
  12763. };
  12764. FilesInput.prototype.renderFunction = function () {
  12765. if (this.additionnalRenderLoopLogicCallback) {
  12766. this.additionnalRenderLoopLogicCallback();
  12767. }
  12768. if (this.currentScene) {
  12769. if (this.textureLoadingCallback) {
  12770. var remaining = this.currentScene.getWaitingItemsCount();
  12771. if (remaining > 0) {
  12772. this.textureLoadingCallback(remaining);
  12773. }
  12774. }
  12775. this.currentScene.render();
  12776. }
  12777. };
  12778. FilesInput.prototype.drag = function (e) {
  12779. e.stopPropagation();
  12780. e.preventDefault();
  12781. };
  12782. FilesInput.prototype.drop = function (eventDrop) {
  12783. eventDrop.stopPropagation();
  12784. eventDrop.preventDefault();
  12785. this.loadFiles(eventDrop);
  12786. };
  12787. FilesInput.prototype.loadFiles = function (event) {
  12788. var _this = this;
  12789. var that = this;
  12790. if (this.startingProcessingFilesCallback)
  12791. this.startingProcessingFilesCallback();
  12792. var sceneFileToLoad;
  12793. var filesToLoad;
  12794. if (event && event.dataTransfer && event.dataTransfer.files) {
  12795. filesToLoad = event.dataTransfer.files;
  12796. }
  12797. if (event && event.target && event.target.files) {
  12798. filesToLoad = event.target.files;
  12799. }
  12800. if (filesToLoad && filesToLoad.length > 0) {
  12801. for (var i = 0; i < filesToLoad.length; i++) {
  12802. switch (filesToLoad[i].type) {
  12803. case "image/jpeg":
  12804. case "image/png":
  12805. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12806. break;
  12807. case "image/targa":
  12808. case "image/vnd.ms-dds":
  12809. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12810. break;
  12811. default:
  12812. 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) {
  12813. sceneFileToLoad = filesToLoad[i];
  12814. }
  12815. break;
  12816. }
  12817. }
  12818. if (sceneFileToLoad) {
  12819. if (this.currentScene) {
  12820. this.engine.stopRenderLoop();
  12821. this.currentScene.dispose();
  12822. }
  12823. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12824. that.currentScene = newScene;
  12825. that.currentScene.executeWhenReady(function () {
  12826. if (that.currentScene.activeCamera) {
  12827. that.currentScene.activeCamera.attachControl(that.canvas);
  12828. }
  12829. if (that.sceneLoadedCallback) {
  12830. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12831. }
  12832. that.engine.runRenderLoop(function () {
  12833. that.renderFunction();
  12834. });
  12835. });
  12836. }, function (progress) {
  12837. if (_this.progressCallback) {
  12838. _this.progressCallback(progress);
  12839. }
  12840. });
  12841. } else {
  12842. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12843. }
  12844. }
  12845. };
  12846. FilesInput.FilesTextures = new Array();
  12847. FilesInput.FilesToLoad = new Array();
  12848. return FilesInput;
  12849. })();
  12850. BABYLON.FilesInput = FilesInput;
  12851. })(BABYLON || (BABYLON = {}));
  12852. var BABYLON;
  12853. (function (BABYLON) {
  12854. var OimoJSPlugin = (function () {
  12855. function OimoJSPlugin() {
  12856. this._registeredMeshes = [];
  12857. /**
  12858. * Update the body position according to the mesh position
  12859. * @param mesh
  12860. */
  12861. this.updateBodyPosition = function (mesh) {
  12862. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12863. var registeredMesh = this._registeredMeshes[index];
  12864. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12865. var body = registeredMesh.body.body;
  12866. var center = mesh.getBoundingInfo().boundingBox.center;
  12867. body.setPosition(center.x, center.y, center.z);
  12868. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12869. return;
  12870. }
  12871. if (registeredMesh.mesh.parent === mesh) {
  12872. mesh.computeWorldMatrix(true);
  12873. registeredMesh.mesh.computeWorldMatrix(true);
  12874. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12875. var absoluteRotation = mesh.rotation;
  12876. body = registeredMesh.body.body;
  12877. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12878. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12879. return;
  12880. }
  12881. }
  12882. };
  12883. }
  12884. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12885. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12886. };
  12887. OimoJSPlugin.prototype.initialize = function (iterations) {
  12888. this._world = new OIMO.World();
  12889. this._world.clear();
  12890. };
  12891. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12892. this._world.gravity = gravity;
  12893. };
  12894. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12895. var body = null;
  12896. this.unregisterMesh(mesh);
  12897. mesh.computeWorldMatrix(true);
  12898. switch (impostor) {
  12899. case BABYLON.PhysicsEngine.SphereImpostor:
  12900. var bbox = mesh.getBoundingInfo().boundingBox;
  12901. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12902. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12903. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12904. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12905. var deltaPosition = mesh.position.subtract(bbox.center);
  12906. body = new OIMO.Body({
  12907. type: 'sphere',
  12908. size: [size],
  12909. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12910. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12911. move: options.mass != 0,
  12912. config: [options.mass, options.friction, options.restitution],
  12913. world: this._world
  12914. });
  12915. this._registeredMeshes.push({
  12916. mesh: mesh,
  12917. body: body,
  12918. delta: deltaPosition
  12919. });
  12920. break;
  12921. case BABYLON.PhysicsEngine.PlaneImpostor:
  12922. case BABYLON.PhysicsEngine.BoxImpostor:
  12923. bbox = mesh.getBoundingInfo().boundingBox;
  12924. var min = bbox.minimumWorld;
  12925. var max = bbox.maximumWorld;
  12926. var box = max.subtract(min);
  12927. var sizeX = this._checkWithEpsilon(box.x);
  12928. var sizeY = this._checkWithEpsilon(box.y);
  12929. var sizeZ = this._checkWithEpsilon(box.z);
  12930. var deltaPosition = mesh.position.subtract(bbox.center);
  12931. body = new OIMO.Body({
  12932. type: 'box',
  12933. size: [sizeX, sizeY, sizeZ],
  12934. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12935. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12936. move: options.mass != 0,
  12937. config: [options.mass, options.friction, options.restitution],
  12938. world: this._world
  12939. });
  12940. this._registeredMeshes.push({
  12941. mesh: mesh,
  12942. body: body,
  12943. delta: deltaPosition
  12944. });
  12945. break;
  12946. }
  12947. return body;
  12948. };
  12949. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12950. var types = [], sizes = [], positions = [], rotations = [];
  12951. var initialMesh = parts[0].mesh;
  12952. for (var index = 0; index < parts.length; index++) {
  12953. var part = parts[index];
  12954. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12955. types.push(bodyParameters.type);
  12956. sizes.push.apply(sizes, bodyParameters.size);
  12957. positions.push.apply(positions, bodyParameters.pos);
  12958. rotations.push.apply(rotations, bodyParameters.rot);
  12959. }
  12960. var body = new OIMO.Body({
  12961. type: types,
  12962. size: sizes,
  12963. pos: positions,
  12964. rot: rotations,
  12965. move: options.mass != 0,
  12966. config: [options.mass, options.friction, options.restitution],
  12967. world: this._world
  12968. });
  12969. this._registeredMeshes.push({
  12970. mesh: initialMesh,
  12971. body: body
  12972. });
  12973. return body;
  12974. };
  12975. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12976. var bodyParameters = null;
  12977. var mesh = part.mesh;
  12978. switch (part.impostor) {
  12979. case BABYLON.PhysicsEngine.SphereImpostor:
  12980. var bbox = mesh.getBoundingInfo().boundingBox;
  12981. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12982. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12983. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12984. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12985. bodyParameters = {
  12986. type: 'sphere',
  12987. /* bug with oimo : sphere needs 3 sizes in this case */
  12988. size: [size, -1, -1],
  12989. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  12990. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12991. };
  12992. break;
  12993. case BABYLON.PhysicsEngine.PlaneImpostor:
  12994. case BABYLON.PhysicsEngine.BoxImpostor:
  12995. bbox = mesh.getBoundingInfo().boundingBox;
  12996. var min = bbox.minimumWorld;
  12997. var max = bbox.maximumWorld;
  12998. var box = max.subtract(min);
  12999. var sizeX = this._checkWithEpsilon(box.x);
  13000. var sizeY = this._checkWithEpsilon(box.y);
  13001. var sizeZ = this._checkWithEpsilon(box.z);
  13002. var relativePosition = mesh.position;
  13003. bodyParameters = {
  13004. type: 'box',
  13005. size: [sizeX, sizeY, sizeZ],
  13006. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13007. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13008. };
  13009. break;
  13010. }
  13011. return bodyParameters;
  13012. };
  13013. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13014. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13015. var registeredMesh = this._registeredMeshes[index];
  13016. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13017. if (registeredMesh.body) {
  13018. this._world.removeRigidBody(registeredMesh.body.body);
  13019. this._unbindBody(registeredMesh.body);
  13020. }
  13021. this._registeredMeshes.splice(index, 1);
  13022. return;
  13023. }
  13024. }
  13025. };
  13026. OimoJSPlugin.prototype._unbindBody = function (body) {
  13027. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13028. var registeredMesh = this._registeredMeshes[index];
  13029. if (registeredMesh.body === body) {
  13030. registeredMesh.body = null;
  13031. }
  13032. }
  13033. };
  13034. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13035. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13036. var registeredMesh = this._registeredMeshes[index];
  13037. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13038. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  13039. return;
  13040. }
  13041. }
  13042. };
  13043. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13044. var body1 = null, body2 = null;
  13045. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13046. var registeredMesh = this._registeredMeshes[index];
  13047. if (registeredMesh.mesh === mesh1) {
  13048. body1 = registeredMesh.body.body;
  13049. } else if (registeredMesh.mesh === mesh2) {
  13050. body2 = registeredMesh.body.body;
  13051. }
  13052. }
  13053. if (!body1 || !body2) {
  13054. return false;
  13055. }
  13056. if (!options) {
  13057. options = {};
  13058. }
  13059. new OIMO.Link({
  13060. type: options.type,
  13061. body1: body1,
  13062. body2: body2,
  13063. min: options.min,
  13064. max: options.max,
  13065. axe1: options.axe1,
  13066. axe2: options.axe2,
  13067. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13068. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13069. collision: options.collision,
  13070. spring: options.spring,
  13071. world: this._world
  13072. });
  13073. return true;
  13074. };
  13075. OimoJSPlugin.prototype.dispose = function () {
  13076. this._world.clear();
  13077. while (this._registeredMeshes.length) {
  13078. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13079. }
  13080. };
  13081. OimoJSPlugin.prototype.isSupported = function () {
  13082. return OIMO !== undefined;
  13083. };
  13084. OimoJSPlugin.prototype._getLastShape = function (body) {
  13085. var lastShape = body.shapes;
  13086. while (lastShape.next) {
  13087. lastShape = lastShape.next;
  13088. }
  13089. return lastShape;
  13090. };
  13091. OimoJSPlugin.prototype.runOneStep = function (time) {
  13092. this._world.step();
  13093. var i = this._registeredMeshes.length;
  13094. var m;
  13095. while (i--) {
  13096. var body = this._registeredMeshes[i].body.body;
  13097. var mesh = this._registeredMeshes[i].mesh;
  13098. var delta = this._registeredMeshes[i].delta;
  13099. if (!body.sleeping) {
  13100. if (body.shapes.next) {
  13101. var parentShape = this._getLastShape(body);
  13102. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13103. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13104. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13105. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13106. if (!mesh.rotationQuaternion) {
  13107. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13108. }
  13109. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13110. } else {
  13111. m = body.getMatrix();
  13112. mtx = BABYLON.Matrix.FromArray(m);
  13113. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13114. if (!delta) {
  13115. mesh.position.x = bodyX;
  13116. mesh.position.y = bodyY;
  13117. mesh.position.z = bodyZ;
  13118. } else {
  13119. mesh.position.x = bodyX + delta.x;
  13120. mesh.position.y = bodyY + delta.y;
  13121. mesh.position.z = bodyZ + delta.z;
  13122. }
  13123. if (!mesh.rotationQuaternion) {
  13124. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13125. }
  13126. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13127. }
  13128. }
  13129. }
  13130. };
  13131. return OimoJSPlugin;
  13132. })();
  13133. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13134. })(BABYLON || (BABYLON = {}));
  13135. var BABYLON;
  13136. (function (BABYLON) {
  13137. var PhysicsEngine = (function () {
  13138. function PhysicsEngine(plugin) {
  13139. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13140. }
  13141. PhysicsEngine.prototype._initialize = function (gravity) {
  13142. this._currentPlugin.initialize();
  13143. this._setGravity(gravity);
  13144. };
  13145. PhysicsEngine.prototype._runOneStep = function (delta) {
  13146. if (delta > 0.1) {
  13147. delta = 0.1;
  13148. } else if (delta <= 0) {
  13149. delta = 1.0 / 60.0;
  13150. }
  13151. this._currentPlugin.runOneStep(delta);
  13152. };
  13153. PhysicsEngine.prototype._setGravity = function (gravity) {
  13154. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13155. this._currentPlugin.setGravity(this.gravity);
  13156. };
  13157. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13158. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13159. };
  13160. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13161. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13162. };
  13163. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13164. this._currentPlugin.unregisterMesh(mesh);
  13165. };
  13166. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13167. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13168. };
  13169. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13170. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13171. };
  13172. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13173. this._currentPlugin.updateBodyPosition(mesh);
  13174. };
  13175. PhysicsEngine.prototype.dispose = function () {
  13176. this._currentPlugin.dispose();
  13177. };
  13178. PhysicsEngine.prototype.isSupported = function () {
  13179. return this._currentPlugin.isSupported();
  13180. };
  13181. PhysicsEngine.NoImpostor = 0;
  13182. PhysicsEngine.SphereImpostor = 1;
  13183. PhysicsEngine.BoxImpostor = 2;
  13184. PhysicsEngine.PlaneImpostor = 3;
  13185. PhysicsEngine.CompoundImpostor = 4;
  13186. PhysicsEngine.MeshImpostor = 4;
  13187. PhysicsEngine.CapsuleImpostor = 5;
  13188. PhysicsEngine.ConeImpostor = 6;
  13189. PhysicsEngine.CylinderImpostor = 7;
  13190. PhysicsEngine.ConvexHullImpostor = 8;
  13191. PhysicsEngine.Epsilon = 0.001;
  13192. return PhysicsEngine;
  13193. })();
  13194. BABYLON.PhysicsEngine = PhysicsEngine;
  13195. })(BABYLON || (BABYLON = {}));
  13196. var BABYLON;
  13197. (function (BABYLON) {
  13198. var serializeLight = function (light) {
  13199. var serializationObject = {};
  13200. serializationObject.name = light.name;
  13201. serializationObject.id = light.id;
  13202. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13203. if (light instanceof BABYLON.PointLight) {
  13204. serializationObject.type = 0;
  13205. serializationObject.position = light.position.asArray();
  13206. } else if (light instanceof BABYLON.DirectionalLight) {
  13207. serializationObject.type = 1;
  13208. var directionalLight = light;
  13209. serializationObject.position = directionalLight.position.asArray();
  13210. serializationObject.direction = directionalLight.direction.asArray();
  13211. } else if (light instanceof BABYLON.SpotLight) {
  13212. serializationObject.type = 2;
  13213. var spotLight = light;
  13214. serializationObject.position = spotLight.position.asArray();
  13215. serializationObject.direction = spotLight.position.asArray();
  13216. serializationObject.angle = spotLight.angle;
  13217. serializationObject.exponent = spotLight.exponent;
  13218. } else if (light instanceof BABYLON.HemisphericLight) {
  13219. serializationObject.type = 3;
  13220. var hemisphericLight = light;
  13221. serializationObject.direction = hemisphericLight.direction.asArray();
  13222. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13223. }
  13224. if (light.intensity) {
  13225. serializationObject.intensity = light.intensity;
  13226. }
  13227. serializationObject.range = light.range;
  13228. serializationObject.diffuse = light.diffuse.asArray();
  13229. serializationObject.specular = light.specular.asArray();
  13230. return serializationObject;
  13231. };
  13232. var serializeFresnelParameter = function (fresnelParameter) {
  13233. var serializationObject = {};
  13234. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13235. serializationObject.leftColor = fresnelParameter.leftColor;
  13236. serializationObject.rightColor = fresnelParameter.rightColor;
  13237. serializationObject.bias = fresnelParameter.bias;
  13238. serializationObject.power = fresnelParameter.power;
  13239. return serializationObject;
  13240. };
  13241. var serializeCamera = function (camera) {
  13242. var serializationObject = {};
  13243. serializationObject.name = camera.name;
  13244. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13245. serializationObject.id = camera.id;
  13246. serializationObject.position = camera.position.asArray();
  13247. if (camera.parent) {
  13248. serializationObject.parentId = camera.parent.id;
  13249. }
  13250. serializationObject.rotation = camera.rotation.asArray();
  13251. if (camera.lockedTarget && camera.lockedTarget.id) {
  13252. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13253. }
  13254. serializationObject.fov = camera.fov;
  13255. serializationObject.minZ = camera.minZ;
  13256. serializationObject.maxZ = camera.maxZ;
  13257. serializationObject.speed = camera.speed;
  13258. serializationObject.inertia = camera.inertia;
  13259. serializationObject.checkCollisions = camera.checkCollisions;
  13260. serializationObject.applyGravity = camera.applyGravity;
  13261. if (camera.ellipsoid) {
  13262. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13263. }
  13264. appendAnimations(camera, serializationObject);
  13265. serializationObject.layerMask = camera.layerMask;
  13266. return serializationObject;
  13267. };
  13268. var appendAnimations = function (source, destination) {
  13269. if (source.animations) {
  13270. destination.animations = [];
  13271. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13272. var animation = source.animations[animationIndex];
  13273. destination.animations.push(serializeAnimation(animation));
  13274. }
  13275. }
  13276. };
  13277. var serializeAnimation = function (animation) {
  13278. var serializationObject = {};
  13279. serializationObject.name = animation.name;
  13280. serializationObject.property = animation.targetProperty;
  13281. serializationObject.framePerSecond = animation.framePerSecond;
  13282. serializationObject.dataType = animation.dataType;
  13283. serializationObject.loopBehavior = animation.loopMode;
  13284. var dataType = animation.dataType;
  13285. serializationObject.keys = [];
  13286. var keys = animation.getKeys();
  13287. for (var index = 0; index < keys.length; index++) {
  13288. var animationKey = keys[index];
  13289. var key = {};
  13290. key.frame = animationKey.frame;
  13291. switch (dataType) {
  13292. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13293. key.values = [animationKey.value];
  13294. break;
  13295. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13296. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13297. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13298. key.values = animationKey.value.asArray();
  13299. break;
  13300. }
  13301. serializationObject.keys.push(key);
  13302. }
  13303. return serializationObject;
  13304. };
  13305. var serializeMultiMaterial = function (material) {
  13306. var serializationObject = {};
  13307. serializationObject.name = material.name;
  13308. serializationObject.id = material.id;
  13309. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13310. serializationObject.materials = [];
  13311. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13312. var subMat = material.subMaterials[matIndex];
  13313. if (subMat) {
  13314. serializationObject.materials.push(subMat.id);
  13315. } else {
  13316. serializationObject.materials.push(null);
  13317. }
  13318. }
  13319. return serializationObject;
  13320. };
  13321. var serializeMaterial = function (material) {
  13322. var serializationObject = {};
  13323. serializationObject.name = material.name;
  13324. serializationObject.ambient = material.ambientColor.asArray();
  13325. serializationObject.diffuse = material.diffuseColor.asArray();
  13326. serializationObject.specular = material.specularColor.asArray();
  13327. serializationObject.specularPower = material.specularPower;
  13328. serializationObject.emissive = material.emissiveColor.asArray();
  13329. serializationObject.alpha = material.alpha;
  13330. serializationObject.id = material.id;
  13331. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13332. serializationObject.backFaceCulling = material.backFaceCulling;
  13333. if (material.diffuseTexture) {
  13334. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13335. }
  13336. if (material.diffuseFresnelParameters) {
  13337. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13338. }
  13339. if (material.ambientTexture) {
  13340. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13341. }
  13342. if (material.opacityTexture) {
  13343. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13344. }
  13345. if (material.opacityFresnelParameters) {
  13346. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13347. }
  13348. if (material.reflectionTexture) {
  13349. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13350. }
  13351. if (material.reflectionFresnelParameters) {
  13352. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13353. }
  13354. if (material.emissiveTexture) {
  13355. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13356. }
  13357. if (material.emissiveFresnelParameters) {
  13358. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13359. }
  13360. if (material.specularTexture) {
  13361. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13362. }
  13363. if (material.bumpTexture) {
  13364. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13365. }
  13366. return serializationObject;
  13367. };
  13368. var serializeTexture = function (texture) {
  13369. var serializationObject = {};
  13370. if (!texture.name) {
  13371. return null;
  13372. }
  13373. if (texture instanceof BABYLON.CubeTexture) {
  13374. serializationObject.name = texture.name;
  13375. serializationObject.hasAlpha = texture.hasAlpha;
  13376. serializationObject.level = texture.level;
  13377. serializationObject.coordinatesMode = texture.coordinatesMode;
  13378. return serializationObject;
  13379. }
  13380. if (texture instanceof BABYLON.MirrorTexture) {
  13381. var mirrorTexture = texture;
  13382. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13383. serializationObject.renderList = [];
  13384. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13385. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13386. }
  13387. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13388. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13389. var renderTargetTexture = texture;
  13390. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13391. serializationObject.renderList = [];
  13392. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13393. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13394. }
  13395. }
  13396. var regularTexture = texture;
  13397. serializationObject.name = texture.name;
  13398. serializationObject.hasAlpha = texture.hasAlpha;
  13399. serializationObject.level = texture.level;
  13400. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13401. serializationObject.coordinatesMode = texture.coordinatesMode;
  13402. serializationObject.uOffset = regularTexture.uOffset;
  13403. serializationObject.vOffset = regularTexture.vOffset;
  13404. serializationObject.uScale = regularTexture.uScale;
  13405. serializationObject.vScale = regularTexture.vScale;
  13406. serializationObject.uAng = regularTexture.uAng;
  13407. serializationObject.vAng = regularTexture.vAng;
  13408. serializationObject.wAng = regularTexture.wAng;
  13409. serializationObject.wrapU = texture.wrapU;
  13410. serializationObject.wrapV = texture.wrapV;
  13411. appendAnimations(texture, serializationObject);
  13412. return serializationObject;
  13413. };
  13414. var serializeSkeleton = function (skeleton) {
  13415. var serializationObject = {};
  13416. serializationObject.name = skeleton.name;
  13417. serializationObject.id = skeleton.id;
  13418. serializationObject.bones = [];
  13419. for (var index = 0; index < skeleton.bones.length; index++) {
  13420. var bone = skeleton.bones[index];
  13421. var serializedBone = {
  13422. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13423. name: bone.name,
  13424. matrix: bone.getLocalMatrix().toArray()
  13425. };
  13426. serializationObject.bones.push(serializedBone);
  13427. if (bone.animations && bone.animations.length > 0) {
  13428. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13429. }
  13430. }
  13431. return serializationObject;
  13432. };
  13433. var serializeParticleSystem = function (particleSystem) {
  13434. var serializationObject = {};
  13435. serializationObject.emitterId = particleSystem.emitter.id;
  13436. serializationObject.capacity = particleSystem.getCapacity();
  13437. if (particleSystem.particleTexture) {
  13438. serializationObject.textureName = particleSystem.particleTexture.name;
  13439. }
  13440. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13441. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13442. serializationObject.minSize = particleSystem.minSize;
  13443. serializationObject.maxSize = particleSystem.maxSize;
  13444. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13445. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13446. serializationObject.emitRate = particleSystem.emitRate;
  13447. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13448. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13449. serializationObject.gravity = particleSystem.gravity.asArray();
  13450. serializationObject.direction1 = particleSystem.direction1.asArray();
  13451. serializationObject.direction2 = particleSystem.direction2.asArray();
  13452. serializationObject.color1 = particleSystem.color1.asArray();
  13453. serializationObject.color2 = particleSystem.color2.asArray();
  13454. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13455. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13456. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13457. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13458. serializationObject.blendMode = particleSystem.blendMode;
  13459. return serializationObject;
  13460. };
  13461. var serializeLensFlareSystem = function (lensFlareSystem) {
  13462. var serializationObject = {};
  13463. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13464. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13465. serializationObject.flares = [];
  13466. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13467. var flare = lensFlareSystem.lensFlares[index];
  13468. serializationObject.flares.push({
  13469. size: flare.size,
  13470. position: flare.position,
  13471. color: flare.color.asArray(),
  13472. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13473. });
  13474. }
  13475. return serializationObject;
  13476. };
  13477. var serializeShadowGenerator = function (light) {
  13478. var serializationObject = {};
  13479. var shadowGenerator = light.getShadowGenerator();
  13480. serializationObject.lightId = light.id;
  13481. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13482. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13483. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13484. serializationObject.renderList = [];
  13485. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13486. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13487. serializationObject.renderList.push(mesh.id);
  13488. }
  13489. return serializationObject;
  13490. };
  13491. var serializedGeometries = [];
  13492. var serializeGeometry = function (geometry, serializationGeometries) {
  13493. if (serializedGeometries[geometry.id]) {
  13494. return;
  13495. }
  13496. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13497. serializationGeometries.boxes.push(serializeBox(geometry));
  13498. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13499. serializationGeometries.spheres.push(serializeSphere(geometry));
  13500. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13501. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13502. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13503. serializationGeometries.toruses.push(serializeTorus(geometry));
  13504. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13505. serializationGeometries.grounds.push(serializeGround(geometry));
  13506. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13507. serializationGeometries.planes.push(serializePlane(geometry));
  13508. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13509. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13510. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13511. throw new Error("Unknow primitive type");
  13512. } else {
  13513. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13514. }
  13515. serializedGeometries[geometry.id] = true;
  13516. };
  13517. var serializeGeometryBase = function (geometry) {
  13518. var serializationObject = {};
  13519. serializationObject.id = geometry.id;
  13520. if (BABYLON.Tags.HasTags(geometry)) {
  13521. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13522. }
  13523. return serializationObject;
  13524. };
  13525. var serializeVertexData = function (vertexData) {
  13526. var serializationObject = serializeGeometryBase(vertexData);
  13527. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13528. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13529. }
  13530. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13531. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13532. }
  13533. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13534. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13535. }
  13536. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13537. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13538. }
  13539. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13540. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13541. }
  13542. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13543. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13544. serializationObject.matricesIndices._isExpanded = true;
  13545. }
  13546. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13547. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13548. }
  13549. serializationObject.indices = vertexData.getIndices();
  13550. return serializationObject;
  13551. };
  13552. var serializePrimitive = function (primitive) {
  13553. var serializationObject = serializeGeometryBase(primitive);
  13554. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13555. return serializationObject;
  13556. };
  13557. var serializeBox = function (box) {
  13558. var serializationObject = serializePrimitive(box);
  13559. serializationObject.size = box.size;
  13560. return serializationObject;
  13561. };
  13562. var serializeSphere = function (sphere) {
  13563. var serializationObject = serializePrimitive(sphere);
  13564. serializationObject.segments = sphere.segments;
  13565. serializationObject.diameter = sphere.diameter;
  13566. return serializationObject;
  13567. };
  13568. var serializeCylinder = function (cylinder) {
  13569. var serializationObject = serializePrimitive(cylinder);
  13570. serializationObject.height = cylinder.height;
  13571. serializationObject.diameterTop = cylinder.diameterTop;
  13572. serializationObject.diameterBottom = cylinder.diameterBottom;
  13573. serializationObject.tessellation = cylinder.tessellation;
  13574. return serializationObject;
  13575. };
  13576. var serializeTorus = function (torus) {
  13577. var serializationObject = serializePrimitive(torus);
  13578. serializationObject.diameter = torus.diameter;
  13579. serializationObject.thickness = torus.thickness;
  13580. serializationObject.tessellation = torus.tessellation;
  13581. return serializationObject;
  13582. };
  13583. var serializeGround = function (ground) {
  13584. var serializationObject = serializePrimitive(ground);
  13585. serializationObject.width = ground.width;
  13586. serializationObject.height = ground.height;
  13587. serializationObject.subdivisions = ground.subdivisions;
  13588. return serializationObject;
  13589. };
  13590. var serializePlane = function (plane) {
  13591. var serializationObject = serializePrimitive(plane);
  13592. serializationObject.size = plane.size;
  13593. return serializationObject;
  13594. };
  13595. var serializeTorusKnot = function (torusKnot) {
  13596. var serializationObject = serializePrimitive(torusKnot);
  13597. serializationObject.radius = torusKnot.radius;
  13598. serializationObject.tube = torusKnot.tube;
  13599. serializationObject.radialSegments = torusKnot.radialSegments;
  13600. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13601. serializationObject.p = torusKnot.p;
  13602. serializationObject.q = torusKnot.q;
  13603. return serializationObject;
  13604. };
  13605. var serializeMesh = function (mesh, serializationScene) {
  13606. var serializationObject = {};
  13607. serializationObject.name = mesh.name;
  13608. serializationObject.id = mesh.id;
  13609. if (BABYLON.Tags.HasTags(mesh)) {
  13610. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13611. }
  13612. serializationObject.position = mesh.position.asArray();
  13613. if (mesh.rotationQuaternion) {
  13614. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13615. } else if (mesh.rotation) {
  13616. serializationObject.rotation = mesh.rotation.asArray();
  13617. }
  13618. serializationObject.scaling = mesh.scaling.asArray();
  13619. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13620. serializationObject.isEnabled = mesh.isEnabled();
  13621. serializationObject.isVisible = mesh.isVisible;
  13622. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13623. serializationObject.pickable = mesh.isPickable;
  13624. serializationObject.receiveShadows = mesh.receiveShadows;
  13625. serializationObject.billboardMode = mesh.billboardMode;
  13626. serializationObject.visibility = mesh.visibility;
  13627. serializationObject.checkCollisions = mesh.checkCollisions;
  13628. if (mesh.parent) {
  13629. serializationObject.parentId = mesh.parent.id;
  13630. }
  13631. var geometry = mesh._geometry;
  13632. if (geometry) {
  13633. var geometryId = geometry.id;
  13634. serializationObject.geometryId = geometryId;
  13635. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13636. serializeGeometry(geometry, serializationScene.geometries);
  13637. }
  13638. serializationObject.subMeshes = [];
  13639. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13640. var subMesh = mesh.subMeshes[subIndex];
  13641. serializationObject.subMeshes.push({
  13642. materialIndex: subMesh.materialIndex,
  13643. verticesStart: subMesh.verticesStart,
  13644. verticesCount: subMesh.verticesCount,
  13645. indexStart: subMesh.indexStart,
  13646. indexCount: subMesh.indexCount
  13647. });
  13648. }
  13649. }
  13650. if (mesh.material) {
  13651. serializationObject.materialId = mesh.material.id;
  13652. } else {
  13653. mesh.material = null;
  13654. }
  13655. if (mesh.skeleton) {
  13656. serializationObject.skeletonId = mesh.skeleton.id;
  13657. }
  13658. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13659. serializationObject.physicsMass = mesh.getPhysicsMass();
  13660. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13661. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13662. switch (mesh.getPhysicsImpostor()) {
  13663. case BABYLON.PhysicsEngine.BoxImpostor:
  13664. serializationObject.physicsImpostor = 1;
  13665. break;
  13666. case BABYLON.PhysicsEngine.SphereImpostor:
  13667. serializationObject.physicsImpostor = 2;
  13668. break;
  13669. }
  13670. }
  13671. serializationObject.instances = [];
  13672. for (var index = 0; index < mesh.instances.length; index++) {
  13673. var instance = mesh.instances[index];
  13674. var serializationInstance = {
  13675. name: instance.name,
  13676. position: instance.position,
  13677. rotation: instance.rotation,
  13678. rotationQuaternion: instance.rotationQuaternion,
  13679. scaling: instance.scaling
  13680. };
  13681. serializationObject.instances.push(serializationInstance);
  13682. appendAnimations(instance, serializationInstance);
  13683. }
  13684. appendAnimations(mesh, serializationObject);
  13685. serializationObject.layerMask = mesh.layerMask;
  13686. return serializationObject;
  13687. };
  13688. var SceneSerializer = (function () {
  13689. function SceneSerializer() {
  13690. }
  13691. SceneSerializer.Serialize = function (scene) {
  13692. var serializationObject = {};
  13693. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13694. serializationObject.autoClear = scene.autoClear;
  13695. serializationObject.clearColor = scene.clearColor.asArray();
  13696. serializationObject.ambientColor = scene.ambientColor.asArray();
  13697. serializationObject.gravity = scene.gravity.asArray();
  13698. if (scene.fogMode && scene.fogMode !== 0) {
  13699. serializationObject.fogMode = scene.fogMode;
  13700. serializationObject.fogColor = scene.fogColor.asArray();
  13701. serializationObject.fogStart = scene.fogStart;
  13702. serializationObject.fogEnd = scene.fogEnd;
  13703. serializationObject.fogDensity = scene.fogDensity;
  13704. }
  13705. serializationObject.lights = [];
  13706. for (var index = 0; index < scene.lights.length; index++) {
  13707. var light = scene.lights[index];
  13708. serializationObject.lights.push(serializeLight(light));
  13709. }
  13710. serializationObject.cameras = [];
  13711. for (index = 0; index < scene.cameras.length; index++) {
  13712. var camera = scene.cameras[index];
  13713. if (camera instanceof BABYLON.FreeCamera) {
  13714. serializationObject.cameras.push(serializeCamera(camera));
  13715. }
  13716. }
  13717. if (scene.activeCamera) {
  13718. serializationObject.activeCameraID = scene.activeCamera.id;
  13719. }
  13720. serializationObject.materials = [];
  13721. serializationObject.multiMaterials = [];
  13722. for (index = 0; index < scene.materials.length; index++) {
  13723. var material = scene.materials[index];
  13724. if (material instanceof BABYLON.StandardMaterial) {
  13725. serializationObject.materials.push(serializeMaterial(material));
  13726. } else if (material instanceof BABYLON.MultiMaterial) {
  13727. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13728. }
  13729. }
  13730. serializationObject.skeletons = [];
  13731. for (index = 0; index < scene.skeletons.length; index++) {
  13732. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13733. }
  13734. serializationObject.geometries = {};
  13735. serializationObject.geometries.boxes = [];
  13736. serializationObject.geometries.spheres = [];
  13737. serializationObject.geometries.cylinders = [];
  13738. serializationObject.geometries.toruses = [];
  13739. serializationObject.geometries.grounds = [];
  13740. serializationObject.geometries.planes = [];
  13741. serializationObject.geometries.torusKnots = [];
  13742. serializationObject.geometries.vertexData = [];
  13743. serializedGeometries = [];
  13744. var geometries = scene.getGeometries();
  13745. for (var index = 0; index < geometries.length; index++) {
  13746. var geometry = geometries[index];
  13747. if (geometry.isReady()) {
  13748. serializeGeometry(geometry, serializationObject.geometries);
  13749. }
  13750. }
  13751. serializationObject.meshes = [];
  13752. for (index = 0; index < scene.meshes.length; index++) {
  13753. var abstractMesh = scene.meshes[index];
  13754. if (abstractMesh instanceof BABYLON.Mesh) {
  13755. var mesh = abstractMesh;
  13756. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13757. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13758. }
  13759. }
  13760. }
  13761. serializationObject.particleSystems = [];
  13762. for (index = 0; index < scene.particleSystems.length; index++) {
  13763. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13764. }
  13765. serializationObject.lensFlareSystems = [];
  13766. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13767. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13768. }
  13769. serializationObject.shadowGenerators = [];
  13770. for (index = 0; index < scene.lights.length; index++) {
  13771. light = scene.lights[index];
  13772. if (light.getShadowGenerator()) {
  13773. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13774. }
  13775. }
  13776. return serializationObject;
  13777. };
  13778. return SceneSerializer;
  13779. })();
  13780. BABYLON.SceneSerializer = SceneSerializer;
  13781. })(BABYLON || (BABYLON = {}));
  13782. var BABYLON;
  13783. (function (BABYLON) {
  13784. var SceneLoader = (function () {
  13785. function SceneLoader() {
  13786. }
  13787. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13788. get: function () {
  13789. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13790. },
  13791. set: function (value) {
  13792. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13793. },
  13794. enumerable: true,
  13795. configurable: true
  13796. });
  13797. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13798. get: function () {
  13799. return SceneLoader._ShowLoadingScreen;
  13800. },
  13801. set: function (value) {
  13802. SceneLoader._ShowLoadingScreen = value;
  13803. },
  13804. enumerable: true,
  13805. configurable: true
  13806. });
  13807. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13808. var dotPosition = sceneFilename.lastIndexOf(".");
  13809. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13810. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13811. var plugin = this._registeredPlugins[index];
  13812. if (plugin.extensions.indexOf(extension) !== -1) {
  13813. return plugin;
  13814. }
  13815. }
  13816. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13817. };
  13818. SceneLoader.RegisterPlugin = function (plugin) {
  13819. plugin.extensions = plugin.extensions.toLowerCase();
  13820. SceneLoader._registeredPlugins.push(plugin);
  13821. };
  13822. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13823. var _this = this;
  13824. var manifestChecked = function (success) {
  13825. scene.database = database;
  13826. var plugin = _this._getPluginForFilename(sceneFilename);
  13827. var importMeshFromData = function (data) {
  13828. var meshes = [];
  13829. var particleSystems = [];
  13830. var skeletons = [];
  13831. try {
  13832. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13833. if (onerror) {
  13834. onerror(scene);
  13835. }
  13836. return;
  13837. }
  13838. } catch (e) {
  13839. if (onerror) {
  13840. onerror(scene);
  13841. }
  13842. return;
  13843. }
  13844. if (onsuccess) {
  13845. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13846. onsuccess(meshes, particleSystems, skeletons);
  13847. }
  13848. };
  13849. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13850. importMeshFromData(sceneFilename.substr(5));
  13851. return;
  13852. }
  13853. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13854. importMeshFromData(data);
  13855. }, progressCallBack, database);
  13856. };
  13857. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13858. };
  13859. /**
  13860. * Load a scene
  13861. * @param rootUrl a string that defines the root url for scene and resources
  13862. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13863. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13864. */
  13865. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13866. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13867. };
  13868. /**
  13869. * Append a scene
  13870. * @param rootUrl a string that defines the root url for scene and resources
  13871. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13872. * @param scene is the instance of BABYLON.Scene to append to
  13873. */
  13874. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13875. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13876. var database;
  13877. if (SceneLoader.ShowLoadingScreen) {
  13878. scene.getEngine().displayLoadingUI();
  13879. }
  13880. var loadSceneFromData = function (data) {
  13881. scene.database = database;
  13882. if (!plugin.load(scene, data, rootUrl)) {
  13883. if (onerror) {
  13884. onerror(scene);
  13885. }
  13886. scene.getEngine().hideLoadingUI();
  13887. return;
  13888. }
  13889. if (onsuccess) {
  13890. onsuccess(scene);
  13891. }
  13892. if (SceneLoader.ShowLoadingScreen) {
  13893. scene.executeWhenReady(function () {
  13894. scene.getEngine().hideLoadingUI();
  13895. });
  13896. }
  13897. };
  13898. var manifestChecked = function (success) {
  13899. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13900. };
  13901. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13902. loadSceneFromData(sceneFilename.substr(5));
  13903. return;
  13904. }
  13905. if (rootUrl.indexOf("file:") === -1) {
  13906. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13907. } else {
  13908. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13909. }
  13910. };
  13911. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13912. SceneLoader._ShowLoadingScreen = true;
  13913. SceneLoader._registeredPlugins = new Array();
  13914. return SceneLoader;
  13915. })();
  13916. BABYLON.SceneLoader = SceneLoader;
  13917. ;
  13918. })(BABYLON || (BABYLON = {}));
  13919. var BABYLON;
  13920. (function (BABYLON) {
  13921. (function (Internals) {
  13922. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13923. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13924. texture.name = parsedTexture.name;
  13925. texture.hasAlpha = parsedTexture.hasAlpha;
  13926. texture.level = parsedTexture.level;
  13927. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13928. return texture;
  13929. };
  13930. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13931. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13932. return null;
  13933. }
  13934. if (parsedTexture.isCube) {
  13935. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13936. }
  13937. var texture;
  13938. if (parsedTexture.mirrorPlane) {
  13939. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13940. texture._waitingRenderList = parsedTexture.renderList;
  13941. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13942. } else if (parsedTexture.isRenderTarget) {
  13943. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13944. texture._waitingRenderList = parsedTexture.renderList;
  13945. } else {
  13946. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13947. }
  13948. texture.name = parsedTexture.name;
  13949. texture.hasAlpha = parsedTexture.hasAlpha;
  13950. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13951. texture.level = parsedTexture.level;
  13952. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13953. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13954. texture.uOffset = parsedTexture.uOffset;
  13955. texture.vOffset = parsedTexture.vOffset;
  13956. texture.uScale = parsedTexture.uScale;
  13957. texture.vScale = parsedTexture.vScale;
  13958. texture.uAng = parsedTexture.uAng;
  13959. texture.vAng = parsedTexture.vAng;
  13960. texture.wAng = parsedTexture.wAng;
  13961. texture.wrapU = parsedTexture.wrapU;
  13962. texture.wrapV = parsedTexture.wrapV;
  13963. if (parsedTexture.animations) {
  13964. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13965. var parsedAnimation = parsedTexture.animations[animationIndex];
  13966. texture.animations.push(parseAnimation(parsedAnimation));
  13967. }
  13968. }
  13969. return texture;
  13970. };
  13971. var parseSkeleton = function (parsedSkeleton, scene) {
  13972. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13973. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13974. var parsedBone = parsedSkeleton.bones[index];
  13975. var parentBone = null;
  13976. if (parsedBone.parentBoneIndex > -1) {
  13977. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13978. }
  13979. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13980. if (parsedBone.animation) {
  13981. bone.animations.push(parseAnimation(parsedBone.animation));
  13982. }
  13983. }
  13984. return skeleton;
  13985. };
  13986. var parseFresnelParameters = function (parsedFresnelParameters) {
  13987. var fresnelParameters = new BABYLON.FresnelParameters();
  13988. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  13989. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  13990. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  13991. fresnelParameters.bias = parsedFresnelParameters.bias;
  13992. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  13993. return fresnelParameters;
  13994. };
  13995. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  13996. var material;
  13997. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  13998. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  13999. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14000. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14001. material.specularPower = parsedMaterial.specularPower;
  14002. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14003. material.alpha = parsedMaterial.alpha;
  14004. material.id = parsedMaterial.id;
  14005. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14006. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14007. material.wireframe = parsedMaterial.wireframe;
  14008. if (parsedMaterial.diffuseTexture) {
  14009. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14010. }
  14011. if (parsedMaterial.diffuseFresnelParameters) {
  14012. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14013. }
  14014. if (parsedMaterial.ambientTexture) {
  14015. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14016. }
  14017. if (parsedMaterial.opacityTexture) {
  14018. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14019. }
  14020. if (parsedMaterial.opacityFresnelParameters) {
  14021. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14022. }
  14023. if (parsedMaterial.reflectionTexture) {
  14024. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14025. }
  14026. if (parsedMaterial.reflectionFresnelParameters) {
  14027. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14028. }
  14029. if (parsedMaterial.emissiveTexture) {
  14030. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14031. }
  14032. if (parsedMaterial.emissiveFresnelParameters) {
  14033. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14034. }
  14035. if (parsedMaterial.specularTexture) {
  14036. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14037. }
  14038. if (parsedMaterial.bumpTexture) {
  14039. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14040. }
  14041. return material;
  14042. };
  14043. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14044. for (var index = 0; index < parsedData.materials.length; index++) {
  14045. var parsedMaterial = parsedData.materials[index];
  14046. if (parsedMaterial.id === id) {
  14047. return parseMaterial(parsedMaterial, scene, rootUrl);
  14048. }
  14049. }
  14050. return null;
  14051. };
  14052. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14053. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14054. multiMaterial.id = parsedMultiMaterial.id;
  14055. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14056. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14057. var subMatId = parsedMultiMaterial.materials[matIndex];
  14058. if (subMatId) {
  14059. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14060. } else {
  14061. multiMaterial.subMaterials.push(null);
  14062. }
  14063. }
  14064. return multiMaterial;
  14065. };
  14066. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14067. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14068. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14069. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14070. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14071. var parsedFlare = parsedLensFlareSystem.flares[index];
  14072. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14073. }
  14074. return lensFlareSystem;
  14075. };
  14076. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14077. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14078. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14079. if (parsedParticleSystem.textureName) {
  14080. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14081. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14082. }
  14083. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14084. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14085. particleSystem.minSize = parsedParticleSystem.minSize;
  14086. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14087. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14088. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14089. particleSystem.emitter = emitter;
  14090. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14091. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14092. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14093. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14094. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14095. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14096. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14097. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14098. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14099. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14100. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14101. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14102. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14103. particleSystem.start();
  14104. return particleSystem;
  14105. };
  14106. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14107. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14108. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14109. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14110. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14111. shadowGenerator.getShadowMap().renderList.push(mesh);
  14112. }
  14113. if (parsedShadowGenerator.usePoissonSampling) {
  14114. shadowGenerator.usePoissonSampling = true;
  14115. } else {
  14116. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14117. }
  14118. return shadowGenerator;
  14119. };
  14120. var parseAnimation = function (parsedAnimation) {
  14121. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14122. var dataType = parsedAnimation.dataType;
  14123. var keys = [];
  14124. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14125. var key = parsedAnimation.keys[index];
  14126. var data;
  14127. switch (dataType) {
  14128. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14129. data = key.values[0];
  14130. break;
  14131. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14132. data = BABYLON.Quaternion.FromArray(key.values);
  14133. break;
  14134. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14135. data = BABYLON.Matrix.FromArray(key.values);
  14136. break;
  14137. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14138. default:
  14139. data = BABYLON.Vector3.FromArray(key.values);
  14140. break;
  14141. }
  14142. keys.push({
  14143. frame: key.frame,
  14144. value: data
  14145. });
  14146. }
  14147. animation.setKeys(keys);
  14148. return animation;
  14149. };
  14150. var parseLight = function (parsedLight, scene) {
  14151. var light;
  14152. switch (parsedLight.type) {
  14153. case 0:
  14154. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14155. break;
  14156. case 1:
  14157. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14158. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14159. break;
  14160. case 2:
  14161. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14162. break;
  14163. case 3:
  14164. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14165. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14166. break;
  14167. }
  14168. light.id = parsedLight.id;
  14169. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14170. if (parsedLight.intensity !== undefined) {
  14171. light.intensity = parsedLight.intensity;
  14172. }
  14173. if (parsedLight.range) {
  14174. light.range = parsedLight.range;
  14175. }
  14176. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14177. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14178. if (parsedLight.excludedMeshesIds) {
  14179. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14180. }
  14181. if (parsedLight.includedOnlyMeshesIds) {
  14182. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14183. }
  14184. if (parsedLight.animations) {
  14185. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14186. var parsedAnimation = parsedLight.animations[animationIndex];
  14187. light.animations.push(parseAnimation(parsedAnimation));
  14188. }
  14189. }
  14190. if (parsedLight.autoAnimate) {
  14191. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14192. }
  14193. };
  14194. var parseCamera = function (parsedCamera, scene) {
  14195. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14196. camera.id = parsedCamera.id;
  14197. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14198. if (parsedCamera.parentId) {
  14199. camera._waitingParentId = parsedCamera.parentId;
  14200. }
  14201. if (parsedCamera.target) {
  14202. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14203. } else {
  14204. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14205. }
  14206. if (parsedCamera.lockedTargetId) {
  14207. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14208. }
  14209. camera.fov = parsedCamera.fov;
  14210. camera.minZ = parsedCamera.minZ;
  14211. camera.maxZ = parsedCamera.maxZ;
  14212. camera.speed = parsedCamera.speed;
  14213. camera.inertia = parsedCamera.inertia;
  14214. camera.checkCollisions = parsedCamera.checkCollisions;
  14215. camera.applyGravity = parsedCamera.applyGravity;
  14216. if (parsedCamera.ellipsoid) {
  14217. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14218. }
  14219. if (parsedCamera.animations) {
  14220. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14221. var parsedAnimation = parsedCamera.animations[animationIndex];
  14222. camera.animations.push(parseAnimation(parsedAnimation));
  14223. }
  14224. }
  14225. if (parsedCamera.autoAnimate) {
  14226. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14227. }
  14228. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14229. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14230. } else {
  14231. camera.layerMask = 0xFFFFFFFF;
  14232. }
  14233. return camera;
  14234. };
  14235. var parseGeometry = function (parsedGeometry, scene) {
  14236. var id = parsedGeometry.id;
  14237. return scene.getGeometryByID(id);
  14238. };
  14239. var parseBox = function (parsedBox, scene) {
  14240. if (parseGeometry(parsedBox, scene)) {
  14241. return null;
  14242. }
  14243. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14244. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14245. scene.pushGeometry(box, true);
  14246. return box;
  14247. };
  14248. var parseSphere = function (parsedSphere, scene) {
  14249. if (parseGeometry(parsedSphere, scene)) {
  14250. return null;
  14251. }
  14252. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14253. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14254. scene.pushGeometry(sphere, true);
  14255. return sphere;
  14256. };
  14257. var parseCylinder = function (parsedCylinder, scene) {
  14258. if (parseGeometry(parsedCylinder, scene)) {
  14259. return null;
  14260. }
  14261. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14262. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14263. scene.pushGeometry(cylinder, true);
  14264. return cylinder;
  14265. };
  14266. var parseTorus = function (parsedTorus, scene) {
  14267. if (parseGeometry(parsedTorus, scene)) {
  14268. return null;
  14269. }
  14270. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14271. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14272. scene.pushGeometry(torus, true);
  14273. return torus;
  14274. };
  14275. var parseGround = function (parsedGround, scene) {
  14276. if (parseGeometry(parsedGround, scene)) {
  14277. return null;
  14278. }
  14279. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14280. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14281. scene.pushGeometry(ground, true);
  14282. return ground;
  14283. };
  14284. var parsePlane = function (parsedPlane, scene) {
  14285. if (parseGeometry(parsedPlane, scene)) {
  14286. return null;
  14287. }
  14288. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14289. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14290. scene.pushGeometry(plane, true);
  14291. return plane;
  14292. };
  14293. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14294. if (parseGeometry(parsedTorusKnot, scene)) {
  14295. return null;
  14296. }
  14297. 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);
  14298. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14299. scene.pushGeometry(torusKnot, true);
  14300. return torusKnot;
  14301. };
  14302. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14303. if (parseGeometry(parsedVertexData, scene)) {
  14304. return null;
  14305. }
  14306. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14307. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14308. if (parsedVertexData.delayLoadingFile) {
  14309. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14310. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14311. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14312. geometry._delayInfo = [];
  14313. if (parsedVertexData.hasUVs) {
  14314. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14315. }
  14316. if (parsedVertexData.hasUVs2) {
  14317. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14318. }
  14319. if (parsedVertexData.hasColors) {
  14320. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14321. }
  14322. if (parsedVertexData.hasMatricesIndices) {
  14323. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14324. }
  14325. if (parsedVertexData.hasMatricesWeights) {
  14326. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14327. }
  14328. geometry._delayLoadingFunction = importVertexData;
  14329. } else {
  14330. importVertexData(parsedVertexData, geometry);
  14331. }
  14332. scene.pushGeometry(geometry, true);
  14333. return geometry;
  14334. };
  14335. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14336. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14337. mesh.id = parsedMesh.id;
  14338. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14339. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14340. if (parsedMesh.rotationQuaternion) {
  14341. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14342. } else if (parsedMesh.rotation) {
  14343. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14344. }
  14345. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14346. if (parsedMesh.localMatrix) {
  14347. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14348. } else if (parsedMesh.pivotMatrix) {
  14349. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14350. }
  14351. mesh.setEnabled(parsedMesh.isEnabled);
  14352. mesh.isVisible = parsedMesh.isVisible;
  14353. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14354. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14355. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14356. if (parsedMesh.pickable !== undefined) {
  14357. mesh.isPickable = parsedMesh.pickable;
  14358. }
  14359. mesh.receiveShadows = parsedMesh.receiveShadows;
  14360. mesh.billboardMode = parsedMesh.billboardMode;
  14361. if (parsedMesh.visibility !== undefined) {
  14362. mesh.visibility = parsedMesh.visibility;
  14363. }
  14364. mesh.checkCollisions = parsedMesh.checkCollisions;
  14365. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14366. if (parsedMesh.parentId) {
  14367. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14368. }
  14369. if (parsedMesh.delayLoadingFile) {
  14370. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14371. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14372. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14373. mesh._delayInfo = [];
  14374. if (parsedMesh.hasUVs) {
  14375. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14376. }
  14377. if (parsedMesh.hasUVs2) {
  14378. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14379. }
  14380. if (parsedMesh.hasColors) {
  14381. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14382. }
  14383. if (parsedMesh.hasMatricesIndices) {
  14384. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14385. }
  14386. if (parsedMesh.hasMatricesWeights) {
  14387. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14388. }
  14389. mesh._delayLoadingFunction = importGeometry;
  14390. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14391. mesh._checkDelayState();
  14392. }
  14393. } else {
  14394. importGeometry(parsedMesh, mesh);
  14395. }
  14396. if (parsedMesh.materialId) {
  14397. mesh.setMaterialByID(parsedMesh.materialId);
  14398. } else {
  14399. mesh.material = null;
  14400. }
  14401. if (parsedMesh.skeletonId > -1) {
  14402. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14403. }
  14404. if (parsedMesh.physicsImpostor) {
  14405. if (!scene.isPhysicsEnabled()) {
  14406. scene.enablePhysics();
  14407. }
  14408. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14409. }
  14410. if (parsedMesh.animations) {
  14411. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14412. var parsedAnimation = parsedMesh.animations[animationIndex];
  14413. mesh.animations.push(parseAnimation(parsedAnimation));
  14414. }
  14415. }
  14416. if (parsedMesh.autoAnimate) {
  14417. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14418. }
  14419. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14420. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14421. } else {
  14422. mesh.layerMask = 0xFFFFFFFF;
  14423. }
  14424. if (parsedMesh.instances) {
  14425. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14426. var parsedInstance = parsedMesh.instances[index];
  14427. var instance = mesh.createInstance(parsedInstance.name);
  14428. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14429. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14430. if (parsedInstance.rotationQuaternion) {
  14431. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14432. } else if (parsedInstance.rotation) {
  14433. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14434. }
  14435. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14436. instance.checkCollisions = mesh.checkCollisions;
  14437. if (parsedMesh.animations) {
  14438. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14439. parsedAnimation = parsedMesh.animations[animationIndex];
  14440. instance.animations.push(parseAnimation(parsedAnimation));
  14441. }
  14442. }
  14443. }
  14444. }
  14445. return mesh;
  14446. };
  14447. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14448. names = (names instanceof Array) ? names : [names];
  14449. for (var i in names) {
  14450. if (mesh.name === names[i]) {
  14451. hierarchyIds.push(mesh.id);
  14452. return true;
  14453. }
  14454. }
  14455. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14456. hierarchyIds.push(mesh.id);
  14457. return true;
  14458. }
  14459. return false;
  14460. };
  14461. var importVertexData = function (parsedVertexData, geometry) {
  14462. var vertexData = new BABYLON.VertexData();
  14463. var positions = parsedVertexData.positions;
  14464. if (positions) {
  14465. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14466. }
  14467. var normals = parsedVertexData.normals;
  14468. if (normals) {
  14469. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14470. }
  14471. var uvs = parsedVertexData.uvs;
  14472. if (uvs) {
  14473. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14474. }
  14475. var uv2s = parsedVertexData.uv2s;
  14476. if (uv2s) {
  14477. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14478. }
  14479. var colors = parsedVertexData.colors;
  14480. if (colors) {
  14481. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14482. }
  14483. var matricesIndices = parsedVertexData.matricesIndices;
  14484. if (matricesIndices) {
  14485. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14486. }
  14487. var matricesWeights = parsedVertexData.matricesWeights;
  14488. if (matricesWeights) {
  14489. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14490. }
  14491. var indices = parsedVertexData.indices;
  14492. if (indices) {
  14493. vertexData.indices = indices;
  14494. }
  14495. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14496. };
  14497. var importGeometry = function (parsedGeometry, mesh) {
  14498. var scene = mesh.getScene();
  14499. var geometryId = parsedGeometry.geometryId;
  14500. if (geometryId) {
  14501. var geometry = scene.getGeometryByID(geometryId);
  14502. if (geometry) {
  14503. geometry.applyToMesh(mesh);
  14504. }
  14505. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14506. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14507. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14508. if (parsedGeometry.uvs) {
  14509. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14510. }
  14511. if (parsedGeometry.uvs2) {
  14512. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14513. }
  14514. if (parsedGeometry.colors) {
  14515. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14516. }
  14517. if (parsedGeometry.matricesIndices) {
  14518. if (!parsedGeometry.matricesIndices._isExpanded) {
  14519. var floatIndices = [];
  14520. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14521. var matricesIndex = parsedGeometry.matricesIndices[i];
  14522. floatIndices.push(matricesIndex & 0x000000FF);
  14523. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14524. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14525. floatIndices.push(matricesIndex >> 24);
  14526. }
  14527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14528. } else {
  14529. delete parsedGeometry.matricesIndices._isExpanded;
  14530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14531. }
  14532. }
  14533. if (parsedGeometry.matricesWeights) {
  14534. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14535. }
  14536. mesh.setIndices(parsedGeometry.indices);
  14537. }
  14538. if (parsedGeometry.subMeshes) {
  14539. mesh.subMeshes = [];
  14540. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14541. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14542. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14543. }
  14544. }
  14545. if (mesh._shouldGenerateFlatShading) {
  14546. mesh.convertToFlatShadedMesh();
  14547. delete mesh._shouldGenerateFlatShading;
  14548. }
  14549. mesh.computeWorldMatrix(true);
  14550. if (scene._selectionOctree) {
  14551. scene._selectionOctree.addMesh(mesh);
  14552. }
  14553. };
  14554. BABYLON.SceneLoader.RegisterPlugin({
  14555. extensions: ".babylon",
  14556. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14557. var parsedData = JSON.parse(data);
  14558. var loadedSkeletonsIds = [];
  14559. var loadedMaterialsIds = [];
  14560. var hierarchyIds = [];
  14561. for (var index = 0; index < parsedData.meshes.length; index++) {
  14562. var parsedMesh = parsedData.meshes[index];
  14563. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14564. if (meshesNames instanceof Array) {
  14565. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14566. }
  14567. if (parsedMesh.materialId) {
  14568. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14569. if (!materialFound) {
  14570. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14571. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14572. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14573. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14574. var subMatId = parsedMultiMaterial.materials[matIndex];
  14575. loadedMaterialsIds.push(subMatId);
  14576. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14577. }
  14578. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14579. parseMultiMaterial(parsedMultiMaterial, scene);
  14580. materialFound = true;
  14581. break;
  14582. }
  14583. }
  14584. }
  14585. if (!materialFound) {
  14586. loadedMaterialsIds.push(parsedMesh.materialId);
  14587. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14588. }
  14589. }
  14590. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14591. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14592. if (!skeletonAlreadyLoaded) {
  14593. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14594. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14595. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14596. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14597. loadedSkeletonsIds.push(parsedSkeleton.id);
  14598. }
  14599. }
  14600. }
  14601. }
  14602. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14603. meshes.push(mesh);
  14604. }
  14605. }
  14606. if (parsedData.particleSystems) {
  14607. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14608. var parsedParticleSystem = parsedData.particleSystems[index];
  14609. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14610. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14611. }
  14612. }
  14613. }
  14614. return true;
  14615. },
  14616. load: function (scene, data, rootUrl) {
  14617. var parsedData = JSON.parse(data);
  14618. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14619. scene.autoClear = parsedData.autoClear;
  14620. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14621. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14622. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14623. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14624. scene.fogMode = parsedData.fogMode;
  14625. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14626. scene.fogStart = parsedData.fogStart;
  14627. scene.fogEnd = parsedData.fogEnd;
  14628. scene.fogDensity = parsedData.fogDensity;
  14629. }
  14630. for (var index = 0; index < parsedData.lights.length; index++) {
  14631. var parsedLight = parsedData.lights[index];
  14632. parseLight(parsedLight, scene);
  14633. }
  14634. for (index = 0; index < parsedData.cameras.length; index++) {
  14635. var parsedCamera = parsedData.cameras[index];
  14636. parseCamera(parsedCamera, scene);
  14637. }
  14638. if (parsedData.activeCameraID) {
  14639. scene.setActiveCameraByID(parsedData.activeCameraID);
  14640. }
  14641. if (parsedData.materials) {
  14642. for (index = 0; index < parsedData.materials.length; index++) {
  14643. var parsedMaterial = parsedData.materials[index];
  14644. parseMaterial(parsedMaterial, scene, rootUrl);
  14645. }
  14646. }
  14647. if (parsedData.multiMaterials) {
  14648. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14649. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14650. parseMultiMaterial(parsedMultiMaterial, scene);
  14651. }
  14652. }
  14653. if (parsedData.skeletons) {
  14654. for (index = 0; index < parsedData.skeletons.length; index++) {
  14655. var parsedSkeleton = parsedData.skeletons[index];
  14656. parseSkeleton(parsedSkeleton, scene);
  14657. }
  14658. }
  14659. var geometries = parsedData.geometries;
  14660. if (geometries) {
  14661. var boxes = geometries.boxes;
  14662. if (boxes) {
  14663. for (index = 0; index < boxes.length; index++) {
  14664. var parsedBox = boxes[index];
  14665. parseBox(parsedBox, scene);
  14666. }
  14667. }
  14668. var spheres = geometries.spheres;
  14669. if (spheres) {
  14670. for (index = 0; index < spheres.length; index++) {
  14671. var parsedSphere = spheres[index];
  14672. parseSphere(parsedSphere, scene);
  14673. }
  14674. }
  14675. var cylinders = geometries.cylinders;
  14676. if (cylinders) {
  14677. for (index = 0; index < cylinders.length; index++) {
  14678. var parsedCylinder = cylinders[index];
  14679. parseCylinder(parsedCylinder, scene);
  14680. }
  14681. }
  14682. var toruses = geometries.toruses;
  14683. if (toruses) {
  14684. for (index = 0; index < toruses.length; index++) {
  14685. var parsedTorus = toruses[index];
  14686. parseTorus(parsedTorus, scene);
  14687. }
  14688. }
  14689. var grounds = geometries.grounds;
  14690. if (grounds) {
  14691. for (index = 0; index < grounds.length; index++) {
  14692. var parsedGround = grounds[index];
  14693. parseGround(parsedGround, scene);
  14694. }
  14695. }
  14696. var planes = geometries.planes;
  14697. if (planes) {
  14698. for (index = 0; index < planes.length; index++) {
  14699. var parsedPlane = planes[index];
  14700. parsePlane(parsedPlane, scene);
  14701. }
  14702. }
  14703. var torusKnots = geometries.torusKnots;
  14704. if (torusKnots) {
  14705. for (index = 0; index < torusKnots.length; index++) {
  14706. var parsedTorusKnot = torusKnots[index];
  14707. parseTorusKnot(parsedTorusKnot, scene);
  14708. }
  14709. }
  14710. var vertexData = geometries.vertexData;
  14711. if (vertexData) {
  14712. for (index = 0; index < vertexData.length; index++) {
  14713. var parsedVertexData = vertexData[index];
  14714. parseVertexData(parsedVertexData, scene, rootUrl);
  14715. }
  14716. }
  14717. }
  14718. for (index = 0; index < parsedData.meshes.length; index++) {
  14719. var parsedMesh = parsedData.meshes[index];
  14720. parseMesh(parsedMesh, scene, rootUrl);
  14721. }
  14722. for (index = 0; index < scene.cameras.length; index++) {
  14723. var camera = scene.cameras[index];
  14724. if (camera._waitingParentId) {
  14725. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14726. delete camera._waitingParentId;
  14727. }
  14728. if (camera instanceof BABYLON.FreeCamera) {
  14729. var freecamera = camera;
  14730. if (freecamera._waitingLockedTargetId) {
  14731. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14732. delete freecamera._waitingLockedTargetId;
  14733. }
  14734. }
  14735. }
  14736. if (parsedData.particleSystems) {
  14737. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14738. var parsedParticleSystem = parsedData.particleSystems[index];
  14739. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14740. }
  14741. }
  14742. if (parsedData.lensFlareSystems) {
  14743. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14744. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14745. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14746. }
  14747. }
  14748. if (parsedData.shadowGenerators) {
  14749. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14750. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14751. parseShadowGenerator(parsedShadowGenerator, scene);
  14752. }
  14753. }
  14754. return true;
  14755. }
  14756. });
  14757. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14758. var Internals = BABYLON.Internals;
  14759. })(BABYLON || (BABYLON = {}));
  14760. var BABYLON;
  14761. (function (BABYLON) {
  14762. var currentCSGMeshId = 0;
  14763. var Vertex = (function () {
  14764. function Vertex(pos, normal, uv) {
  14765. this.pos = pos;
  14766. this.normal = normal;
  14767. this.uv = uv;
  14768. }
  14769. Vertex.prototype.clone = function () {
  14770. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14771. };
  14772. Vertex.prototype.flip = function () {
  14773. this.normal = this.normal.scale(-1);
  14774. };
  14775. Vertex.prototype.interpolate = function (other, t) {
  14776. 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));
  14777. };
  14778. return Vertex;
  14779. })();
  14780. var Plane = (function () {
  14781. function Plane(normal, w) {
  14782. this.normal = normal;
  14783. this.w = w;
  14784. }
  14785. Plane.FromPoints = function (a, b, c) {
  14786. var v0 = c.subtract(a);
  14787. var v1 = b.subtract(a);
  14788. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14789. return null;
  14790. }
  14791. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14792. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14793. };
  14794. Plane.prototype.clone = function () {
  14795. return new Plane(this.normal.clone(), this.w);
  14796. };
  14797. Plane.prototype.flip = function () {
  14798. this.normal.scaleInPlace(-1);
  14799. this.w = -this.w;
  14800. };
  14801. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14802. var COPLANAR = 0;
  14803. var FRONT = 1;
  14804. var BACK = 2;
  14805. var SPANNING = 3;
  14806. var polygonType = 0;
  14807. var types = [];
  14808. for (var i = 0; i < polygon.vertices.length; i++) {
  14809. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14810. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14811. polygonType |= type;
  14812. types.push(type);
  14813. }
  14814. switch (polygonType) {
  14815. case COPLANAR:
  14816. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14817. break;
  14818. case FRONT:
  14819. front.push(polygon);
  14820. break;
  14821. case BACK:
  14822. back.push(polygon);
  14823. break;
  14824. case SPANNING:
  14825. var f = [], b = [];
  14826. for (i = 0; i < polygon.vertices.length; i++) {
  14827. var j = (i + 1) % polygon.vertices.length;
  14828. var ti = types[i], tj = types[j];
  14829. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14830. if (ti != BACK)
  14831. f.push(vi);
  14832. if (ti != FRONT)
  14833. b.push(ti != BACK ? vi.clone() : vi);
  14834. if ((ti | tj) == SPANNING) {
  14835. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14836. var v = vi.interpolate(vj, t);
  14837. f.push(v);
  14838. b.push(v.clone());
  14839. }
  14840. }
  14841. if (f.length >= 3) {
  14842. var poly = new Polygon(f, polygon.shared);
  14843. if (poly.plane)
  14844. front.push(poly);
  14845. }
  14846. if (b.length >= 3) {
  14847. poly = new Polygon(b, polygon.shared);
  14848. if (poly.plane)
  14849. back.push(poly);
  14850. }
  14851. break;
  14852. }
  14853. };
  14854. Plane.EPSILON = 1e-5;
  14855. return Plane;
  14856. })();
  14857. var Polygon = (function () {
  14858. function Polygon(vertices, shared) {
  14859. this.vertices = vertices;
  14860. this.shared = shared;
  14861. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14862. }
  14863. Polygon.prototype.clone = function () {
  14864. var vertices = this.vertices.map(function (v) {
  14865. return v.clone();
  14866. });
  14867. return new Polygon(vertices, this.shared);
  14868. };
  14869. Polygon.prototype.flip = function () {
  14870. this.vertices.reverse().map(function (v) {
  14871. v.flip();
  14872. });
  14873. this.plane.flip();
  14874. };
  14875. return Polygon;
  14876. })();
  14877. var Node = (function () {
  14878. function Node(polygons) {
  14879. this.plane = null;
  14880. this.front = null;
  14881. this.back = null;
  14882. this.polygons = [];
  14883. if (polygons) {
  14884. this.build(polygons);
  14885. }
  14886. }
  14887. Node.prototype.clone = function () {
  14888. var node = new Node();
  14889. node.plane = this.plane && this.plane.clone();
  14890. node.front = this.front && this.front.clone();
  14891. node.back = this.back && this.back.clone();
  14892. node.polygons = this.polygons.map(function (p) {
  14893. return p.clone();
  14894. });
  14895. return node;
  14896. };
  14897. Node.prototype.invert = function () {
  14898. for (var i = 0; i < this.polygons.length; i++) {
  14899. this.polygons[i].flip();
  14900. }
  14901. if (this.plane) {
  14902. this.plane.flip();
  14903. }
  14904. if (this.front) {
  14905. this.front.invert();
  14906. }
  14907. if (this.back) {
  14908. this.back.invert();
  14909. }
  14910. var temp = this.front;
  14911. this.front = this.back;
  14912. this.back = temp;
  14913. };
  14914. Node.prototype.clipPolygons = function (polygons) {
  14915. if (!this.plane)
  14916. return polygons.slice();
  14917. var front = [], back = [];
  14918. for (var i = 0; i < polygons.length; i++) {
  14919. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14920. }
  14921. if (this.front) {
  14922. front = this.front.clipPolygons(front);
  14923. }
  14924. if (this.back) {
  14925. back = this.back.clipPolygons(back);
  14926. } else {
  14927. back = [];
  14928. }
  14929. return front.concat(back);
  14930. };
  14931. Node.prototype.clipTo = function (bsp) {
  14932. this.polygons = bsp.clipPolygons(this.polygons);
  14933. if (this.front)
  14934. this.front.clipTo(bsp);
  14935. if (this.back)
  14936. this.back.clipTo(bsp);
  14937. };
  14938. Node.prototype.allPolygons = function () {
  14939. var polygons = this.polygons.slice();
  14940. if (this.front)
  14941. polygons = polygons.concat(this.front.allPolygons());
  14942. if (this.back)
  14943. polygons = polygons.concat(this.back.allPolygons());
  14944. return polygons;
  14945. };
  14946. Node.prototype.build = function (polygons) {
  14947. if (!polygons.length)
  14948. return;
  14949. if (!this.plane)
  14950. this.plane = polygons[0].plane.clone();
  14951. var front = [], back = [];
  14952. for (var i = 0; i < polygons.length; i++) {
  14953. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  14954. }
  14955. if (front.length) {
  14956. if (!this.front)
  14957. this.front = new Node();
  14958. this.front.build(front);
  14959. }
  14960. if (back.length) {
  14961. if (!this.back)
  14962. this.back = new Node();
  14963. this.back.build(back);
  14964. }
  14965. };
  14966. return Node;
  14967. })();
  14968. var CSG = (function () {
  14969. function CSG() {
  14970. this.polygons = new Array();
  14971. }
  14972. CSG.FromMesh = function (mesh) {
  14973. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  14974. if (mesh instanceof BABYLON.Mesh) {
  14975. mesh.computeWorldMatrix(true);
  14976. var matrix = mesh.getWorldMatrix();
  14977. var meshPosition = mesh.position.clone();
  14978. var meshRotation = mesh.rotation.clone();
  14979. var meshScaling = mesh.scaling.clone();
  14980. } else {
  14981. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  14982. }
  14983. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14984. var subMeshes = mesh.subMeshes;
  14985. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  14986. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  14987. vertices = [];
  14988. for (var j = 0; j < 3; j++) {
  14989. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  14990. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  14991. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  14992. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  14993. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  14994. vertex = new Vertex(position, normal, uv);
  14995. vertices.push(vertex);
  14996. }
  14997. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  14998. if (polygon.plane)
  14999. polygons.push(polygon);
  15000. }
  15001. }
  15002. var csg = CSG.FromPolygons(polygons);
  15003. csg.matrix = matrix;
  15004. csg.position = meshPosition;
  15005. csg.rotation = meshRotation;
  15006. csg.scaling = meshScaling;
  15007. currentCSGMeshId++;
  15008. return csg;
  15009. };
  15010. CSG.FromPolygons = function (polygons) {
  15011. var csg = new BABYLON.CSG();
  15012. csg.polygons = polygons;
  15013. return csg;
  15014. };
  15015. CSG.prototype.clone = function () {
  15016. var csg = new BABYLON.CSG();
  15017. csg.polygons = this.polygons.map(function (p) {
  15018. return p.clone();
  15019. });
  15020. csg.copyTransformAttributes(this);
  15021. return csg;
  15022. };
  15023. CSG.prototype.toPolygons = function () {
  15024. return this.polygons;
  15025. };
  15026. CSG.prototype.union = function (csg) {
  15027. var a = new Node(this.clone().polygons);
  15028. var b = new Node(csg.clone().polygons);
  15029. a.clipTo(b);
  15030. b.clipTo(a);
  15031. b.invert();
  15032. b.clipTo(a);
  15033. b.invert();
  15034. a.build(b.allPolygons());
  15035. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15036. };
  15037. CSG.prototype.unionInPlace = function (csg) {
  15038. var a = new Node(this.polygons);
  15039. var b = new Node(csg.polygons);
  15040. a.clipTo(b);
  15041. b.clipTo(a);
  15042. b.invert();
  15043. b.clipTo(a);
  15044. b.invert();
  15045. a.build(b.allPolygons());
  15046. this.polygons = a.allPolygons();
  15047. };
  15048. CSG.prototype.subtract = function (csg) {
  15049. var a = new Node(this.clone().polygons);
  15050. var b = new Node(csg.clone().polygons);
  15051. a.invert();
  15052. a.clipTo(b);
  15053. b.clipTo(a);
  15054. b.invert();
  15055. b.clipTo(a);
  15056. b.invert();
  15057. a.build(b.allPolygons());
  15058. a.invert();
  15059. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15060. };
  15061. CSG.prototype.subtractInPlace = function (csg) {
  15062. var a = new Node(this.polygons);
  15063. var b = new Node(csg.polygons);
  15064. a.invert();
  15065. a.clipTo(b);
  15066. b.clipTo(a);
  15067. b.invert();
  15068. b.clipTo(a);
  15069. b.invert();
  15070. a.build(b.allPolygons());
  15071. a.invert();
  15072. this.polygons = a.allPolygons();
  15073. };
  15074. CSG.prototype.intersect = function (csg) {
  15075. var a = new Node(this.clone().polygons);
  15076. var b = new Node(csg.clone().polygons);
  15077. a.invert();
  15078. b.clipTo(a);
  15079. b.invert();
  15080. a.clipTo(b);
  15081. b.clipTo(a);
  15082. a.build(b.allPolygons());
  15083. a.invert();
  15084. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15085. };
  15086. CSG.prototype.intersectInPlace = function (csg) {
  15087. var a = new Node(this.polygons);
  15088. var b = new Node(csg.polygons);
  15089. a.invert();
  15090. b.clipTo(a);
  15091. b.invert();
  15092. a.clipTo(b);
  15093. b.clipTo(a);
  15094. a.build(b.allPolygons());
  15095. a.invert();
  15096. this.polygons = a.allPolygons();
  15097. };
  15098. CSG.prototype.inverse = function () {
  15099. var csg = this.clone();
  15100. csg.inverseInPlace();
  15101. return csg;
  15102. };
  15103. CSG.prototype.inverseInPlace = function () {
  15104. this.polygons.map(function (p) {
  15105. p.flip();
  15106. });
  15107. };
  15108. CSG.prototype.copyTransformAttributes = function (csg) {
  15109. this.matrix = csg.matrix;
  15110. this.position = csg.position;
  15111. this.rotation = csg.rotation;
  15112. this.scaling = csg.scaling;
  15113. return this;
  15114. };
  15115. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15116. var matrix = this.matrix.clone();
  15117. matrix.invert();
  15118. 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;
  15119. if (keepSubMeshes) {
  15120. polygons.sort(function (a, b) {
  15121. if (a.shared.meshId === b.shared.meshId) {
  15122. return a.shared.subMeshId - b.shared.subMeshId;
  15123. } else {
  15124. return a.shared.meshId - b.shared.meshId;
  15125. }
  15126. });
  15127. }
  15128. for (var i = 0, il = polygons.length; i < il; i++) {
  15129. polygon = polygons[i];
  15130. if (!subMesh_dict[polygon.shared.meshId]) {
  15131. subMesh_dict[polygon.shared.meshId] = {};
  15132. }
  15133. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15134. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15135. indexStart: +Infinity,
  15136. indexEnd: -Infinity,
  15137. materialIndex: polygon.shared.materialIndex
  15138. };
  15139. }
  15140. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15141. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15142. polygonIndices[0] = 0;
  15143. polygonIndices[1] = j - 1;
  15144. polygonIndices[2] = j;
  15145. for (var k = 0; k < 3; k++) {
  15146. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15147. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15148. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15149. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15150. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15151. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15152. 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)) {
  15153. vertices.push(vertex.x, vertex.y, vertex.z);
  15154. uvs.push(uv.x, uv.y);
  15155. normals.push(normal.x, normal.y, normal.z);
  15156. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15157. }
  15158. indices.push(vertex_idx);
  15159. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15160. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15161. currentIndex++;
  15162. }
  15163. }
  15164. }
  15165. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15166. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15167. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15168. mesh.setIndices(indices);
  15169. if (keepSubMeshes) {
  15170. var materialIndexOffset = 0, materialMaxIndex;
  15171. mesh.subMeshes.length = 0;
  15172. for (var m in subMesh_dict) {
  15173. materialMaxIndex = -1;
  15174. for (var sm in subMesh_dict[m]) {
  15175. subMesh_obj = subMesh_dict[m][sm];
  15176. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15177. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15178. }
  15179. materialIndexOffset += ++materialMaxIndex;
  15180. }
  15181. }
  15182. return mesh;
  15183. };
  15184. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15185. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15186. mesh.material = material;
  15187. mesh.position.copyFrom(this.position);
  15188. mesh.rotation.copyFrom(this.rotation);
  15189. mesh.scaling.copyFrom(this.scaling);
  15190. mesh.computeWorldMatrix(true);
  15191. return mesh;
  15192. };
  15193. return CSG;
  15194. })();
  15195. BABYLON.CSG = CSG;
  15196. })(BABYLON || (BABYLON = {}));
  15197. var __extends = this.__extends || function (d, b) {
  15198. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15199. function __() { this.constructor = d; }
  15200. __.prototype = b.prototype;
  15201. d.prototype = new __();
  15202. };
  15203. var BABYLON;
  15204. (function (BABYLON) {
  15205. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15206. __extends(OculusDistortionCorrectionPostProcess, _super);
  15207. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15208. var _this = this;
  15209. _super.call(this, name, "oculusDistortionCorrection", [
  15210. 'LensCenter',
  15211. 'Scale',
  15212. 'ScaleIn',
  15213. 'HmdWarpParam'
  15214. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15215. this._isRightEye = isRightEye;
  15216. this._distortionFactors = cameraSettings.DistortionK;
  15217. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15218. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15219. this.onSizeChanged = function () {
  15220. _this.aspectRatio = _this.width * .5 / _this.height;
  15221. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15222. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15223. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15224. };
  15225. this.onApply = function (effect) {
  15226. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15227. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15228. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15229. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15230. };
  15231. }
  15232. return OculusDistortionCorrectionPostProcess;
  15233. })(BABYLON.PostProcess);
  15234. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15235. })(BABYLON || (BABYLON = {}));
  15236. var BABYLON;
  15237. (function (BABYLON) {
  15238. (function (JoystickAxis) {
  15239. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15240. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15241. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15242. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15243. var JoystickAxis = BABYLON.JoystickAxis;
  15244. var VirtualJoystick = (function () {
  15245. function VirtualJoystick(leftJoystick) {
  15246. var _this = this;
  15247. if (leftJoystick) {
  15248. this._leftJoystick = true;
  15249. } else {
  15250. this._leftJoystick = false;
  15251. }
  15252. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15253. VirtualJoystick._globalJoystickIndex++;
  15254. this._axisTargetedByLeftAndRight = 0 /* X */;
  15255. this._axisTargetedByUpAndDown = 1 /* Y */;
  15256. this.reverseLeftRight = false;
  15257. this.reverseUpDown = false;
  15258. this._touches = new BABYLON.VirtualJoystick.Collection();
  15259. this.deltaPosition = BABYLON.Vector3.Zero();
  15260. this._joystickSensibility = 25;
  15261. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15262. this._rotationSpeed = 25;
  15263. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15264. this._rotateOnAxisRelativeToMesh = false;
  15265. if (!VirtualJoystick.vjCanvas) {
  15266. window.addEventListener("resize", function () {
  15267. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15268. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15269. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15270. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15271. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15272. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15273. }, false);
  15274. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15275. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15276. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15277. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15278. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15279. VirtualJoystick.vjCanvas.style.width = "100%";
  15280. VirtualJoystick.vjCanvas.style.height = "100%";
  15281. VirtualJoystick.vjCanvas.style.position = "absolute";
  15282. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15283. VirtualJoystick.vjCanvas.style.top = "0px";
  15284. VirtualJoystick.vjCanvas.style.left = "0px";
  15285. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15286. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15287. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15288. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15289. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15290. document.body.appendChild(VirtualJoystick.vjCanvas);
  15291. }
  15292. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15293. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15294. this.pressed = false;
  15295. this._joystickColor = "cyan";
  15296. this._joystickPointerID = -1;
  15297. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15298. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15299. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15300. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15301. _this._onPointerDown(evt);
  15302. }, false);
  15303. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15304. _this._onPointerMove(evt);
  15305. }, false);
  15306. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15307. _this._onPointerUp(evt);
  15308. }, false);
  15309. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15310. _this._onPointerUp(evt);
  15311. }, false);
  15312. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15313. evt.preventDefault();
  15314. }, false);
  15315. requestAnimationFrame(function () {
  15316. _this._drawVirtualJoystick();
  15317. });
  15318. }
  15319. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15320. this._joystickSensibility = newJoystickSensibility;
  15321. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15322. };
  15323. VirtualJoystick.prototype._onPointerDown = function (e) {
  15324. var positionOnScreenCondition;
  15325. e.preventDefault();
  15326. if (this._leftJoystick === true) {
  15327. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15328. } else {
  15329. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15330. }
  15331. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15332. this._joystickPointerID = e.pointerId;
  15333. this._joystickPointerStartPos.x = e.clientX;
  15334. this._joystickPointerStartPos.y = e.clientY;
  15335. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15336. this._deltaJoystickVector.x = 0;
  15337. this._deltaJoystickVector.y = 0;
  15338. this.pressed = true;
  15339. this._touches.add(e.pointerId.toString(), e);
  15340. } else {
  15341. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15342. this._action();
  15343. this._touches.add(e.pointerId.toString(), e);
  15344. }
  15345. }
  15346. };
  15347. VirtualJoystick.prototype._onPointerMove = function (e) {
  15348. if (this._joystickPointerID == e.pointerId) {
  15349. this._joystickPointerPos.x = e.clientX;
  15350. this._joystickPointerPos.y = e.clientY;
  15351. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15352. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15353. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15354. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15355. switch (this._axisTargetedByLeftAndRight) {
  15356. case 0 /* X */:
  15357. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15358. break;
  15359. case 1 /* Y */:
  15360. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15361. break;
  15362. case 2 /* Z */:
  15363. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15364. break;
  15365. }
  15366. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15367. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15368. switch (this._axisTargetedByUpAndDown) {
  15369. case 0 /* X */:
  15370. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15371. break;
  15372. case 1 /* Y */:
  15373. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15374. break;
  15375. case 2 /* Z */:
  15376. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15377. break;
  15378. }
  15379. } else {
  15380. if (this._touches.item(e.pointerId.toString())) {
  15381. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15382. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15383. }
  15384. }
  15385. };
  15386. VirtualJoystick.prototype._onPointerUp = function (e) {
  15387. this._clearCanvas();
  15388. if (this._joystickPointerID == e.pointerId) {
  15389. this._joystickPointerID = -1;
  15390. this.pressed = false;
  15391. }
  15392. this._deltaJoystickVector.x = 0;
  15393. this._deltaJoystickVector.y = 0;
  15394. this._touches.remove(e.pointerId.toString());
  15395. };
  15396. /**
  15397. * Change the color of the virtual joystick
  15398. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15399. */
  15400. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15401. this._joystickColor = newColor;
  15402. };
  15403. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15404. this._action = action;
  15405. };
  15406. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15407. switch (axis) {
  15408. case 0 /* X */:
  15409. case 1 /* Y */:
  15410. case 2 /* Z */:
  15411. this._axisTargetedByLeftAndRight = axis;
  15412. break;
  15413. default:
  15414. this._axisTargetedByLeftAndRight = 0 /* X */;
  15415. break;
  15416. }
  15417. };
  15418. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15419. switch (axis) {
  15420. case 0 /* X */:
  15421. case 1 /* Y */:
  15422. case 2 /* Z */:
  15423. this._axisTargetedByUpAndDown = axis;
  15424. break;
  15425. default:
  15426. this._axisTargetedByUpAndDown = 1 /* Y */;
  15427. break;
  15428. }
  15429. };
  15430. VirtualJoystick.prototype._clearCanvas = function () {
  15431. if (this._leftJoystick) {
  15432. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15433. } else {
  15434. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15435. }
  15436. };
  15437. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15438. var _this = this;
  15439. if (this.pressed) {
  15440. this._clearCanvas();
  15441. this._touches.forEach(function (touch) {
  15442. if (touch.pointerId === _this._joystickPointerID) {
  15443. VirtualJoystick.vjCanvasContext.beginPath();
  15444. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15445. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15446. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15447. VirtualJoystick.vjCanvasContext.stroke();
  15448. VirtualJoystick.vjCanvasContext.beginPath();
  15449. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15450. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15451. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15452. VirtualJoystick.vjCanvasContext.stroke();
  15453. VirtualJoystick.vjCanvasContext.beginPath();
  15454. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15455. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15456. VirtualJoystick.vjCanvasContext.stroke();
  15457. } else {
  15458. VirtualJoystick.vjCanvasContext.beginPath();
  15459. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15460. VirtualJoystick.vjCanvasContext.beginPath();
  15461. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15462. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15463. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15464. VirtualJoystick.vjCanvasContext.stroke();
  15465. }
  15466. ;
  15467. });
  15468. }
  15469. requestAnimationFrame(function () {
  15470. _this._drawVirtualJoystick();
  15471. });
  15472. };
  15473. VirtualJoystick.prototype.releaseCanvas = function () {
  15474. if (VirtualJoystick.vjCanvas) {
  15475. document.body.removeChild(VirtualJoystick.vjCanvas);
  15476. VirtualJoystick.vjCanvas = null;
  15477. }
  15478. };
  15479. VirtualJoystick._globalJoystickIndex = 0;
  15480. return VirtualJoystick;
  15481. })();
  15482. BABYLON.VirtualJoystick = VirtualJoystick;
  15483. })(BABYLON || (BABYLON = {}));
  15484. var BABYLON;
  15485. (function (BABYLON) {
  15486. (function (VirtualJoystick) {
  15487. var Collection = (function () {
  15488. function Collection() {
  15489. this._count = 0;
  15490. this._collection = new Array();
  15491. }
  15492. Collection.prototype.Count = function () {
  15493. return this._count;
  15494. };
  15495. Collection.prototype.add = function (key, item) {
  15496. if (this._collection[key] != undefined) {
  15497. return undefined;
  15498. }
  15499. this._collection[key] = item;
  15500. return ++this._count;
  15501. };
  15502. Collection.prototype.remove = function (key) {
  15503. if (this._collection[key] == undefined) {
  15504. return undefined;
  15505. }
  15506. delete this._collection[key];
  15507. return --this._count;
  15508. };
  15509. Collection.prototype.item = function (key) {
  15510. return this._collection[key];
  15511. };
  15512. Collection.prototype.forEach = function (block) {
  15513. var key;
  15514. for (key in this._collection) {
  15515. if (this._collection.hasOwnProperty(key)) {
  15516. block(this._collection[key]);
  15517. }
  15518. }
  15519. };
  15520. return Collection;
  15521. })();
  15522. VirtualJoystick.Collection = Collection;
  15523. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15524. var VirtualJoystick = BABYLON.VirtualJoystick;
  15525. })(BABYLON || (BABYLON = {}));
  15526. var __extends = this.__extends || function (d, b) {
  15527. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15528. function __() { this.constructor = d; }
  15529. __.prototype = b.prototype;
  15530. d.prototype = new __();
  15531. };
  15532. var BABYLON;
  15533. (function (BABYLON) {
  15534. var OculusRiftDevKit2013_Metric = {
  15535. HResolution: 1280,
  15536. VResolution: 800,
  15537. HScreenSize: 0.149759993,
  15538. VScreenSize: 0.0935999975,
  15539. VScreenCenter: 0.0467999987,
  15540. EyeToScreenDistance: 0.0410000011,
  15541. LensSeparationDistance: 0.0635000020,
  15542. InterpupillaryDistance: 0.0640000030,
  15543. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15544. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15545. PostProcessScaleFactor: 1.714605507808412,
  15546. LensCenterOffset: 0.151976421
  15547. };
  15548. var _OculusInnerCamera = (function (_super) {
  15549. __extends(_OculusInnerCamera, _super);
  15550. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15551. _super.call(this, name, position, scene);
  15552. this._workMatrix = new BABYLON.Matrix();
  15553. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15554. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15555. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15556. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15557. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15558. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15559. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15560. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15561. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15562. }
  15563. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15564. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15565. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15566. return this._projectionMatrix;
  15567. };
  15568. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15569. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15570. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15571. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15572. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15573. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15574. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15575. return this._viewMatrix;
  15576. };
  15577. return _OculusInnerCamera;
  15578. })(BABYLON.FreeCamera);
  15579. var OculusCamera = (function (_super) {
  15580. __extends(OculusCamera, _super);
  15581. function OculusCamera(name, position, scene) {
  15582. _super.call(this, name, position, scene);
  15583. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15584. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15585. this.subCameras.push(this._leftCamera);
  15586. this.subCameras.push(this._rightCamera);
  15587. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15588. }
  15589. OculusCamera.prototype._update = function () {
  15590. this._leftCamera.position.copyFrom(this.position);
  15591. this._rightCamera.position.copyFrom(this.position);
  15592. this._updateCamera(this._leftCamera);
  15593. this._updateCamera(this._rightCamera);
  15594. _super.prototype._update.call(this);
  15595. };
  15596. OculusCamera.prototype._updateCamera = function (camera) {
  15597. camera.minZ = this.minZ;
  15598. camera.maxZ = this.maxZ;
  15599. camera.rotation.x = this.rotation.x;
  15600. camera.rotation.y = this.rotation.y;
  15601. camera.rotation.z = this.rotation.z;
  15602. };
  15603. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15604. var yaw = evt.alpha / 180 * Math.PI;
  15605. var pitch = evt.beta / 180 * Math.PI;
  15606. var roll = evt.gamma / 180 * Math.PI;
  15607. if (!this._offsetOrientation) {
  15608. this._offsetOrientation = {
  15609. yaw: yaw,
  15610. pitch: pitch,
  15611. roll: roll
  15612. };
  15613. return;
  15614. } else {
  15615. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15616. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15617. this.rotation.z += this._offsetOrientation.roll - roll;
  15618. this._offsetOrientation.yaw = yaw;
  15619. this._offsetOrientation.pitch = pitch;
  15620. this._offsetOrientation.roll = roll;
  15621. }
  15622. };
  15623. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15624. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15625. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15626. };
  15627. OculusCamera.prototype.detachControl = function (element) {
  15628. _super.prototype.detachControl.call(this, element);
  15629. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15630. };
  15631. return OculusCamera;
  15632. })(BABYLON.FreeCamera);
  15633. BABYLON.OculusCamera = OculusCamera;
  15634. })(BABYLON || (BABYLON = {}));
  15635. var __extends = this.__extends || function (d, b) {
  15636. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15637. function __() { this.constructor = d; }
  15638. __.prototype = b.prototype;
  15639. d.prototype = new __();
  15640. };
  15641. var BABYLON;
  15642. (function (BABYLON) {
  15643. var VirtualJoysticksCamera = (function (_super) {
  15644. __extends(VirtualJoysticksCamera, _super);
  15645. function VirtualJoysticksCamera(name, position, scene) {
  15646. _super.call(this, name, position, scene);
  15647. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15648. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15649. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15650. this._leftjoystick.setJoystickSensibility(0.15);
  15651. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15652. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15653. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15654. this._rightjoystick.reverseUpDown = true;
  15655. this._rightjoystick.setJoystickSensibility(0.05);
  15656. this._rightjoystick.setJoystickColor("yellow");
  15657. }
  15658. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15659. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15660. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15661. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15662. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15663. if (!this._leftjoystick.pressed) {
  15664. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15665. }
  15666. if (!this._rightjoystick.pressed) {
  15667. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15668. }
  15669. };
  15670. VirtualJoysticksCamera.prototype.dispose = function () {
  15671. this._leftjoystick.releaseCanvas();
  15672. _super.prototype.dispose.call(this);
  15673. };
  15674. return VirtualJoysticksCamera;
  15675. })(BABYLON.FreeCamera);
  15676. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15677. })(BABYLON || (BABYLON = {}));
  15678. var __extends = this.__extends || function (d, b) {
  15679. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15680. function __() { this.constructor = d; }
  15681. __.prototype = b.prototype;
  15682. d.prototype = new __();
  15683. };
  15684. var BABYLON;
  15685. (function (BABYLON) {
  15686. var ShaderMaterial = (function (_super) {
  15687. __extends(ShaderMaterial, _super);
  15688. function ShaderMaterial(name, scene, shaderPath, options) {
  15689. _super.call(this, name, scene);
  15690. this._textures = new Array();
  15691. this._floats = new Array();
  15692. this._floatsArrays = {};
  15693. this._colors3 = new Array();
  15694. this._colors4 = new Array();
  15695. this._vectors2 = new Array();
  15696. this._vectors3 = new Array();
  15697. this._matrices = new Array();
  15698. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15699. this._shaderPath = shaderPath;
  15700. options.needAlphaBlending = options.needAlphaBlending || false;
  15701. options.needAlphaTesting = options.needAlphaTesting || false;
  15702. options.attributes = options.attributes || ["position", "normal", "uv"];
  15703. options.uniforms = options.uniforms || ["worldViewProjection"];
  15704. options.samplers = options.samplers || [];
  15705. this._options = options;
  15706. }
  15707. ShaderMaterial.prototype.needAlphaBlending = function () {
  15708. return this._options.needAlphaBlending;
  15709. };
  15710. ShaderMaterial.prototype.needAlphaTesting = function () {
  15711. return this._options.needAlphaTesting;
  15712. };
  15713. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15714. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15715. this._options.uniforms.push(uniformName);
  15716. }
  15717. };
  15718. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15719. if (this._options.samplers.indexOf(name) === -1) {
  15720. this._options.samplers.push(name);
  15721. }
  15722. this._textures[name] = texture;
  15723. return this;
  15724. };
  15725. ShaderMaterial.prototype.setFloat = function (name, value) {
  15726. this._checkUniform(name);
  15727. this._floats[name] = value;
  15728. return this;
  15729. };
  15730. ShaderMaterial.prototype.setFloats = function (name, value) {
  15731. this._checkUniform(name);
  15732. this._floatsArrays[name] = value;
  15733. return this;
  15734. };
  15735. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15736. this._checkUniform(name);
  15737. this._colors3[name] = value;
  15738. return this;
  15739. };
  15740. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15741. this._checkUniform(name);
  15742. this._colors4[name] = value;
  15743. return this;
  15744. };
  15745. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15746. this._checkUniform(name);
  15747. this._vectors2[name] = value;
  15748. return this;
  15749. };
  15750. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15751. this._checkUniform(name);
  15752. this._vectors3[name] = value;
  15753. return this;
  15754. };
  15755. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15756. this._checkUniform(name);
  15757. this._matrices[name] = value;
  15758. return this;
  15759. };
  15760. ShaderMaterial.prototype.isReady = function () {
  15761. var engine = this.getScene().getEngine();
  15762. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15763. if (!this._effect.isReady()) {
  15764. return false;
  15765. }
  15766. return true;
  15767. };
  15768. ShaderMaterial.prototype.bind = function (world) {
  15769. if (this._options.uniforms.indexOf("world") !== -1) {
  15770. this._effect.setMatrix("world", world);
  15771. }
  15772. if (this._options.uniforms.indexOf("view") !== -1) {
  15773. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15774. }
  15775. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15776. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15777. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15778. }
  15779. if (this._options.uniforms.indexOf("projection") !== -1) {
  15780. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15781. }
  15782. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15783. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15784. }
  15785. for (var name in this._textures) {
  15786. this._effect.setTexture(name, this._textures[name]);
  15787. }
  15788. for (name in this._floats) {
  15789. this._effect.setFloat(name, this._floats[name]);
  15790. }
  15791. for (name in this._floatsArrays) {
  15792. this._effect.setArray(name, this._floatsArrays[name]);
  15793. }
  15794. for (name in this._colors3) {
  15795. this._effect.setColor3(name, this._colors3[name]);
  15796. }
  15797. for (name in this._colors4) {
  15798. var color = this._colors4[name];
  15799. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15800. }
  15801. for (name in this._vectors2) {
  15802. this._effect.setVector2(name, this._vectors2[name]);
  15803. }
  15804. for (name in this._vectors3) {
  15805. this._effect.setVector3(name, this._vectors3[name]);
  15806. }
  15807. for (name in this._matrices) {
  15808. this._effect.setMatrix(name, this._matrices[name]);
  15809. }
  15810. };
  15811. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15812. for (var name in this._textures) {
  15813. this._textures[name].dispose();
  15814. }
  15815. this._textures = [];
  15816. _super.prototype.dispose.call(this, forceDisposeEffect);
  15817. };
  15818. return ShaderMaterial;
  15819. })(BABYLON.Material);
  15820. BABYLON.ShaderMaterial = ShaderMaterial;
  15821. })(BABYLON || (BABYLON = {}));
  15822. var BABYLON;
  15823. (function (BABYLON) {
  15824. var VertexData = (function () {
  15825. function VertexData() {
  15826. }
  15827. VertexData.prototype.set = function (data, kind) {
  15828. switch (kind) {
  15829. case BABYLON.VertexBuffer.PositionKind:
  15830. this.positions = data;
  15831. break;
  15832. case BABYLON.VertexBuffer.NormalKind:
  15833. this.normals = data;
  15834. break;
  15835. case BABYLON.VertexBuffer.UVKind:
  15836. this.uvs = data;
  15837. break;
  15838. case BABYLON.VertexBuffer.UV2Kind:
  15839. this.uv2s = data;
  15840. break;
  15841. case BABYLON.VertexBuffer.ColorKind:
  15842. this.colors = data;
  15843. break;
  15844. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15845. this.matricesIndices = data;
  15846. break;
  15847. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15848. this.matricesWeights = data;
  15849. break;
  15850. }
  15851. };
  15852. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15853. this._applyTo(mesh, updatable);
  15854. };
  15855. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15856. this._applyTo(geometry, updatable);
  15857. };
  15858. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15859. this._update(mesh);
  15860. };
  15861. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15862. this._update(geometry);
  15863. };
  15864. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15865. if (this.positions) {
  15866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15867. }
  15868. if (this.normals) {
  15869. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15870. }
  15871. if (this.uvs) {
  15872. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15873. }
  15874. if (this.uv2s) {
  15875. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15876. }
  15877. if (this.colors) {
  15878. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15879. }
  15880. if (this.matricesIndices) {
  15881. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15882. }
  15883. if (this.matricesWeights) {
  15884. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15885. }
  15886. if (this.indices) {
  15887. meshOrGeometry.setIndices(this.indices);
  15888. }
  15889. };
  15890. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15891. if (this.positions) {
  15892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15893. }
  15894. if (this.normals) {
  15895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15896. }
  15897. if (this.uvs) {
  15898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15899. }
  15900. if (this.uv2s) {
  15901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15902. }
  15903. if (this.colors) {
  15904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15905. }
  15906. if (this.matricesIndices) {
  15907. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15908. }
  15909. if (this.matricesWeights) {
  15910. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15911. }
  15912. if (this.indices) {
  15913. meshOrGeometry.setIndices(this.indices);
  15914. }
  15915. };
  15916. VertexData.prototype.transform = function (matrix) {
  15917. var transformed = BABYLON.Vector3.Zero();
  15918. if (this.positions) {
  15919. var position = BABYLON.Vector3.Zero();
  15920. for (var index = 0; index < this.positions.length; index += 3) {
  15921. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15922. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15923. this.positions[index] = transformed.x;
  15924. this.positions[index + 1] = transformed.y;
  15925. this.positions[index + 2] = transformed.z;
  15926. }
  15927. }
  15928. if (this.normals) {
  15929. var normal = BABYLON.Vector3.Zero();
  15930. for (index = 0; index < this.normals.length; index += 3) {
  15931. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  15932. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  15933. this.normals[index] = transformed.x;
  15934. this.normals[index + 1] = transformed.y;
  15935. this.normals[index + 2] = transformed.z;
  15936. }
  15937. }
  15938. };
  15939. VertexData.prototype.merge = function (other) {
  15940. if (other.indices) {
  15941. if (!this.indices) {
  15942. this.indices = [];
  15943. }
  15944. var offset = this.positions ? this.positions.length / 3 : 0;
  15945. for (var index = 0; index < other.indices.length; index++) {
  15946. this.indices.push(other.indices[index] + offset);
  15947. }
  15948. }
  15949. if (other.positions) {
  15950. if (!this.positions) {
  15951. this.positions = [];
  15952. }
  15953. for (index = 0; index < other.positions.length; index++) {
  15954. this.positions.push(other.positions[index]);
  15955. }
  15956. }
  15957. if (other.normals) {
  15958. if (!this.normals) {
  15959. this.normals = [];
  15960. }
  15961. for (index = 0; index < other.normals.length; index++) {
  15962. this.normals.push(other.normals[index]);
  15963. }
  15964. }
  15965. if (other.uvs) {
  15966. if (!this.uvs) {
  15967. this.uvs = [];
  15968. }
  15969. for (index = 0; index < other.uvs.length; index++) {
  15970. this.uvs.push(other.uvs[index]);
  15971. }
  15972. }
  15973. if (other.uv2s) {
  15974. if (!this.uv2s) {
  15975. this.uv2s = [];
  15976. }
  15977. for (index = 0; index < other.uv2s.length; index++) {
  15978. this.uv2s.push(other.uv2s[index]);
  15979. }
  15980. }
  15981. if (other.matricesIndices) {
  15982. if (!this.matricesIndices) {
  15983. this.matricesIndices = [];
  15984. }
  15985. for (index = 0; index < other.matricesIndices.length; index++) {
  15986. this.matricesIndices.push(other.matricesIndices[index]);
  15987. }
  15988. }
  15989. if (other.matricesWeights) {
  15990. if (!this.matricesWeights) {
  15991. this.matricesWeights = [];
  15992. }
  15993. for (index = 0; index < other.matricesWeights.length; index++) {
  15994. this.matricesWeights.push(other.matricesWeights[index]);
  15995. }
  15996. }
  15997. if (other.colors) {
  15998. if (!this.colors) {
  15999. this.colors = [];
  16000. }
  16001. for (index = 0; index < other.colors.length; index++) {
  16002. this.colors.push(other.colors[index]);
  16003. }
  16004. }
  16005. };
  16006. VertexData.ExtractFromMesh = function (mesh) {
  16007. return VertexData._ExtractFrom(mesh);
  16008. };
  16009. VertexData.ExtractFromGeometry = function (geometry) {
  16010. return VertexData._ExtractFrom(geometry);
  16011. };
  16012. VertexData._ExtractFrom = function (meshOrGeometry) {
  16013. var result = new BABYLON.VertexData();
  16014. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16015. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16016. }
  16017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16018. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16019. }
  16020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16021. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16022. }
  16023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16024. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16025. }
  16026. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16027. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16028. }
  16029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16030. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16031. }
  16032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16033. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16034. }
  16035. result.indices = meshOrGeometry.getIndices();
  16036. return result;
  16037. };
  16038. VertexData.CreateBox = function (size) {
  16039. var normalsSource = [
  16040. new BABYLON.Vector3(0, 0, 1),
  16041. new BABYLON.Vector3(0, 0, -1),
  16042. new BABYLON.Vector3(1, 0, 0),
  16043. new BABYLON.Vector3(-1, 0, 0),
  16044. new BABYLON.Vector3(0, 1, 0),
  16045. new BABYLON.Vector3(0, -1, 0)
  16046. ];
  16047. var indices = [];
  16048. var positions = [];
  16049. var normals = [];
  16050. var uvs = [];
  16051. size = size || 1;
  16052. for (var index = 0; index < normalsSource.length; index++) {
  16053. var normal = normalsSource[index];
  16054. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16055. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16056. var verticesLength = positions.length / 3;
  16057. indices.push(verticesLength);
  16058. indices.push(verticesLength + 1);
  16059. indices.push(verticesLength + 2);
  16060. indices.push(verticesLength);
  16061. indices.push(verticesLength + 2);
  16062. indices.push(verticesLength + 3);
  16063. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16064. positions.push(vertex.x, vertex.y, vertex.z);
  16065. normals.push(normal.x, normal.y, normal.z);
  16066. uvs.push(1.0, 1.0);
  16067. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16068. positions.push(vertex.x, vertex.y, vertex.z);
  16069. normals.push(normal.x, normal.y, normal.z);
  16070. uvs.push(0.0, 1.0);
  16071. vertex = normal.add(side1).add(side2).scale(size / 2);
  16072. positions.push(vertex.x, vertex.y, vertex.z);
  16073. normals.push(normal.x, normal.y, normal.z);
  16074. uvs.push(0.0, 0.0);
  16075. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16076. positions.push(vertex.x, vertex.y, vertex.z);
  16077. normals.push(normal.x, normal.y, normal.z);
  16078. uvs.push(1.0, 0.0);
  16079. }
  16080. var vertexData = new BABYLON.VertexData();
  16081. vertexData.indices = indices;
  16082. vertexData.positions = positions;
  16083. vertexData.normals = normals;
  16084. vertexData.uvs = uvs;
  16085. return vertexData;
  16086. };
  16087. VertexData.CreateSphere = function (segments, diameter) {
  16088. segments = segments || 32;
  16089. diameter = diameter || 1;
  16090. var radius = diameter / 2;
  16091. var totalZRotationSteps = 2 + segments;
  16092. var totalYRotationSteps = 2 * totalZRotationSteps;
  16093. var indices = [];
  16094. var positions = [];
  16095. var normals = [];
  16096. var uvs = [];
  16097. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16098. var normalizedZ = zRotationStep / totalZRotationSteps;
  16099. var angleZ = (normalizedZ * Math.PI);
  16100. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16101. var normalizedY = yRotationStep / totalYRotationSteps;
  16102. var angleY = normalizedY * Math.PI * 2;
  16103. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16104. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16105. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16106. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16107. var vertex = complete.scale(radius);
  16108. var normal = BABYLON.Vector3.Normalize(vertex);
  16109. positions.push(vertex.x, vertex.y, vertex.z);
  16110. normals.push(normal.x, normal.y, normal.z);
  16111. uvs.push(normalizedZ, normalizedY);
  16112. }
  16113. if (zRotationStep > 0) {
  16114. var verticesCount = positions.length / 3;
  16115. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16116. indices.push((firstIndex));
  16117. indices.push((firstIndex + 1));
  16118. indices.push(firstIndex + totalYRotationSteps + 1);
  16119. indices.push((firstIndex + totalYRotationSteps + 1));
  16120. indices.push((firstIndex + 1));
  16121. indices.push((firstIndex + totalYRotationSteps + 2));
  16122. }
  16123. }
  16124. }
  16125. var vertexData = new BABYLON.VertexData();
  16126. vertexData.indices = indices;
  16127. vertexData.positions = positions;
  16128. vertexData.normals = normals;
  16129. vertexData.uvs = uvs;
  16130. return vertexData;
  16131. };
  16132. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16133. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16134. var radiusTop = diameterTop / 2;
  16135. var radiusBottom = diameterBottom / 2;
  16136. var indices = [];
  16137. var positions = [];
  16138. var normals = [];
  16139. var uvs = [];
  16140. height = height || 1;
  16141. diameterTop = diameterTop || 0.5;
  16142. diameterBottom = diameterBottom || 1;
  16143. tessellation = tessellation || 16;
  16144. subdivisions = subdivisions || 1;
  16145. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16146. var getCircleVector = function (i) {
  16147. var angle = (i * 2.0 * Math.PI / tessellation);
  16148. var dx = Math.cos(angle);
  16149. var dz = Math.sin(angle);
  16150. return new BABYLON.Vector3(dx, 0, dz);
  16151. };
  16152. var createCylinderCap = function (isTop) {
  16153. var radius = isTop ? radiusTop : radiusBottom;
  16154. if (radius == 0) {
  16155. return;
  16156. }
  16157. var vbase = positions.length / 3;
  16158. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16159. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16160. if (!isTop) {
  16161. offset.scaleInPlace(-1);
  16162. textureScale.x = -textureScale.x;
  16163. }
  16164. for (i = 0; i < tessellation; i++) {
  16165. var circleVector = getCircleVector(i);
  16166. var position = circleVector.scale(radius).add(offset);
  16167. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16168. positions.push(position.x, position.y, position.z);
  16169. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16170. }
  16171. for (var i = 0; i < tessellation - 2; i++) {
  16172. if (!isTop) {
  16173. indices.push(vbase);
  16174. indices.push(vbase + (i + 2) % tessellation);
  16175. indices.push(vbase + (i + 1) % tessellation);
  16176. } else {
  16177. indices.push(vbase);
  16178. indices.push(vbase + (i + 1) % tessellation);
  16179. indices.push(vbase + (i + 2) % tessellation);
  16180. }
  16181. }
  16182. };
  16183. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16184. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16185. var stride = tessellation + 1;
  16186. for (var i = 0; i <= tessellation; i++) {
  16187. var circleVector = getCircleVector(i);
  16188. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16189. var position, radius = radiusBottom;
  16190. for (var s = 0; s <= subdivisions; s++) {
  16191. position = circleVector.scale(radius);
  16192. position.addInPlace(base.add(offset.scale(s)));
  16193. textureCoordinate.y += 1 / subdivisions;
  16194. radius += (radiusTop - radiusBottom) / subdivisions;
  16195. positions.push(position.x, position.y, position.z);
  16196. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16197. }
  16198. }
  16199. subdivisions += 1;
  16200. for (var s = 0; s < subdivisions - 1; s++) {
  16201. for (var i = 0; i <= tessellation; i++) {
  16202. indices.push(i * subdivisions + s);
  16203. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16204. indices.push(i * subdivisions + (s + 1));
  16205. indices.push(i * subdivisions + (s + 1));
  16206. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16207. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16208. }
  16209. }
  16210. createCylinderCap(true);
  16211. createCylinderCap(false);
  16212. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16213. var vertexData = new BABYLON.VertexData();
  16214. vertexData.indices = indices;
  16215. vertexData.positions = positions;
  16216. vertexData.normals = normals;
  16217. vertexData.uvs = uvs;
  16218. return vertexData;
  16219. };
  16220. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16221. var indices = [];
  16222. var positions = [];
  16223. var normals = [];
  16224. var uvs = [];
  16225. diameter = diameter || 1;
  16226. thickness = thickness || 0.5;
  16227. tessellation = tessellation || 16;
  16228. var stride = tessellation + 1;
  16229. for (var i = 0; i <= tessellation; i++) {
  16230. var u = i / tessellation;
  16231. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16232. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16233. for (var j = 0; j <= tessellation; j++) {
  16234. var v = 1 - j / tessellation;
  16235. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16236. var dx = Math.cos(innerAngle);
  16237. var dy = Math.sin(innerAngle);
  16238. var normal = new BABYLON.Vector3(dx, dy, 0);
  16239. var position = normal.scale(thickness / 2);
  16240. var textureCoordinate = new BABYLON.Vector2(u, v);
  16241. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16242. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16243. positions.push(position.x, position.y, position.z);
  16244. normals.push(normal.x, normal.y, normal.z);
  16245. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16246. var nextI = (i + 1) % stride;
  16247. var nextJ = (j + 1) % stride;
  16248. indices.push(i * stride + j);
  16249. indices.push(i * stride + nextJ);
  16250. indices.push(nextI * stride + j);
  16251. indices.push(i * stride + nextJ);
  16252. indices.push(nextI * stride + nextJ);
  16253. indices.push(nextI * stride + j);
  16254. }
  16255. }
  16256. var vertexData = new BABYLON.VertexData();
  16257. vertexData.indices = indices;
  16258. vertexData.positions = positions;
  16259. vertexData.normals = normals;
  16260. vertexData.uvs = uvs;
  16261. return vertexData;
  16262. };
  16263. VertexData.CreateLines = function (points) {
  16264. var indices = [];
  16265. var positions = [];
  16266. for (var index = 0; index < points.length; index++) {
  16267. positions.push(points[index].x, points[index].y, points[index].z);
  16268. if (index > 0) {
  16269. indices.push(index - 1);
  16270. indices.push(index);
  16271. }
  16272. }
  16273. var vertexData = new BABYLON.VertexData();
  16274. vertexData.indices = indices;
  16275. vertexData.positions = positions;
  16276. return vertexData;
  16277. };
  16278. VertexData.CreateGround = function (width, height, subdivisions) {
  16279. var indices = [];
  16280. var positions = [];
  16281. var normals = [];
  16282. var uvs = [];
  16283. var row, col;
  16284. width = width || 1;
  16285. height = height || 1;
  16286. subdivisions = subdivisions || 1;
  16287. for (row = 0; row <= subdivisions; row++) {
  16288. for (col = 0; col <= subdivisions; col++) {
  16289. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16290. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16291. positions.push(position.x, position.y, position.z);
  16292. normals.push(normal.x, normal.y, normal.z);
  16293. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16294. }
  16295. }
  16296. for (row = 0; row < subdivisions; row++) {
  16297. for (col = 0; col < subdivisions; col++) {
  16298. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16299. indices.push(col + 1 + row * (subdivisions + 1));
  16300. indices.push(col + row * (subdivisions + 1));
  16301. indices.push(col + (row + 1) * (subdivisions + 1));
  16302. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16303. indices.push(col + row * (subdivisions + 1));
  16304. }
  16305. }
  16306. var vertexData = new BABYLON.VertexData();
  16307. vertexData.indices = indices;
  16308. vertexData.positions = positions;
  16309. vertexData.normals = normals;
  16310. vertexData.uvs = uvs;
  16311. return vertexData;
  16312. };
  16313. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16314. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16315. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16316. var indices = [];
  16317. var positions = [];
  16318. var normals = [];
  16319. var uvs = [];
  16320. var row, col, tileRow, tileCol;
  16321. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16322. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16323. precision.w = (precision.w < 1) ? 1 : precision.w;
  16324. precision.h = (precision.h < 1) ? 1 : precision.h;
  16325. var tileSize = {
  16326. 'w': (xmax - xmin) / subdivisions.w,
  16327. 'h': (zmax - zmin) / subdivisions.h
  16328. };
  16329. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16330. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16331. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16332. }
  16333. }
  16334. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16335. var base = positions.length / 3;
  16336. var rowLength = precision.w + 1;
  16337. for (row = 0; row < precision.h; row++) {
  16338. for (col = 0; col < precision.w; col++) {
  16339. var square = [
  16340. base + col + row * rowLength,
  16341. base + (col + 1) + row * rowLength,
  16342. base + (col + 1) + (row + 1) * rowLength,
  16343. base + col + (row + 1) * rowLength
  16344. ];
  16345. indices.push(square[1]);
  16346. indices.push(square[2]);
  16347. indices.push(square[3]);
  16348. indices.push(square[0]);
  16349. indices.push(square[1]);
  16350. indices.push(square[3]);
  16351. }
  16352. }
  16353. var position = BABYLON.Vector3.Zero();
  16354. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16355. for (row = 0; row <= precision.h; row++) {
  16356. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16357. for (col = 0; col <= precision.w; col++) {
  16358. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16359. position.y = 0;
  16360. positions.push(position.x, position.y, position.z);
  16361. normals.push(normal.x, normal.y, normal.z);
  16362. uvs.push(col / precision.w, row / precision.h);
  16363. }
  16364. }
  16365. }
  16366. var vertexData = new BABYLON.VertexData();
  16367. vertexData.indices = indices;
  16368. vertexData.positions = positions;
  16369. vertexData.normals = normals;
  16370. vertexData.uvs = uvs;
  16371. return vertexData;
  16372. };
  16373. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16374. var indices = [];
  16375. var positions = [];
  16376. var normals = [];
  16377. var uvs = [];
  16378. var row, col;
  16379. for (row = 0; row <= subdivisions; row++) {
  16380. for (col = 0; col <= subdivisions; col++) {
  16381. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16382. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16383. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16384. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16385. var r = buffer[pos] / 255.0;
  16386. var g = buffer[pos + 1] / 255.0;
  16387. var b = buffer[pos + 2] / 255.0;
  16388. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16389. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16390. positions.push(position.x, position.y, position.z);
  16391. normals.push(0, 0, 0);
  16392. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16393. }
  16394. }
  16395. for (row = 0; row < subdivisions; row++) {
  16396. for (col = 0; col < subdivisions; col++) {
  16397. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16398. indices.push(col + 1 + row * (subdivisions + 1));
  16399. indices.push(col + row * (subdivisions + 1));
  16400. indices.push(col + (row + 1) * (subdivisions + 1));
  16401. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16402. indices.push(col + row * (subdivisions + 1));
  16403. }
  16404. }
  16405. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16406. var vertexData = new BABYLON.VertexData();
  16407. vertexData.indices = indices;
  16408. vertexData.positions = positions;
  16409. vertexData.normals = normals;
  16410. vertexData.uvs = uvs;
  16411. return vertexData;
  16412. };
  16413. VertexData.CreatePlane = function (size) {
  16414. var indices = [];
  16415. var positions = [];
  16416. var normals = [];
  16417. var uvs = [];
  16418. size = size || 1;
  16419. var halfSize = size / 2.0;
  16420. positions.push(-halfSize, -halfSize, 0);
  16421. normals.push(0, 0, -1.0);
  16422. uvs.push(0.0, 0.0);
  16423. positions.push(halfSize, -halfSize, 0);
  16424. normals.push(0, 0, -1.0);
  16425. uvs.push(1.0, 0.0);
  16426. positions.push(halfSize, halfSize, 0);
  16427. normals.push(0, 0, -1.0);
  16428. uvs.push(1.0, 1.0);
  16429. positions.push(-halfSize, halfSize, 0);
  16430. normals.push(0, 0, -1.0);
  16431. uvs.push(0.0, 1.0);
  16432. indices.push(0);
  16433. indices.push(1);
  16434. indices.push(2);
  16435. indices.push(0);
  16436. indices.push(2);
  16437. indices.push(3);
  16438. var vertexData = new BABYLON.VertexData();
  16439. vertexData.indices = indices;
  16440. vertexData.positions = positions;
  16441. vertexData.normals = normals;
  16442. vertexData.uvs = uvs;
  16443. return vertexData;
  16444. };
  16445. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16446. var indices = [];
  16447. var positions = [];
  16448. var normals = [];
  16449. var uvs = [];
  16450. radius = radius || 2;
  16451. tube = tube || 0.5;
  16452. radialSegments = radialSegments || 32;
  16453. tubularSegments = tubularSegments || 32;
  16454. p = p || 2;
  16455. q = q || 3;
  16456. var getPos = function (angle) {
  16457. var cu = Math.cos(angle);
  16458. var su = Math.sin(angle);
  16459. var quOverP = q / p * angle;
  16460. var cs = Math.cos(quOverP);
  16461. var tx = radius * (2 + cs) * 0.5 * cu;
  16462. var ty = radius * (2 + cs) * su * 0.5;
  16463. var tz = radius * Math.sin(quOverP) * 0.5;
  16464. return new BABYLON.Vector3(tx, ty, tz);
  16465. };
  16466. for (var i = 0; i <= radialSegments; i++) {
  16467. var modI = i % radialSegments;
  16468. var u = modI / radialSegments * 2 * p * Math.PI;
  16469. var p1 = getPos(u);
  16470. var p2 = getPos(u + 0.01);
  16471. var tang = p2.subtract(p1);
  16472. var n = p2.add(p1);
  16473. var bitan = BABYLON.Vector3.Cross(tang, n);
  16474. n = BABYLON.Vector3.Cross(bitan, tang);
  16475. bitan.normalize();
  16476. n.normalize();
  16477. for (var j = 0; j < tubularSegments; j++) {
  16478. var modJ = j % tubularSegments;
  16479. var v = modJ / tubularSegments * 2 * Math.PI;
  16480. var cx = -tube * Math.cos(v);
  16481. var cy = tube * Math.sin(v);
  16482. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16483. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16484. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16485. uvs.push(i / radialSegments);
  16486. uvs.push(j / tubularSegments);
  16487. }
  16488. }
  16489. for (i = 0; i < radialSegments; i++) {
  16490. for (j = 0; j < tubularSegments; j++) {
  16491. var jNext = (j + 1) % tubularSegments;
  16492. var a = i * tubularSegments + j;
  16493. var b = (i + 1) * tubularSegments + j;
  16494. var c = (i + 1) * tubularSegments + jNext;
  16495. var d = i * tubularSegments + jNext;
  16496. indices.push(d);
  16497. indices.push(b);
  16498. indices.push(a);
  16499. indices.push(d);
  16500. indices.push(c);
  16501. indices.push(b);
  16502. }
  16503. }
  16504. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16505. var vertexData = new BABYLON.VertexData();
  16506. vertexData.indices = indices;
  16507. vertexData.positions = positions;
  16508. vertexData.normals = normals;
  16509. vertexData.uvs = uvs;
  16510. return vertexData;
  16511. };
  16512. VertexData.ComputeNormals = function (positions, indices, normals) {
  16513. var positionVectors = [];
  16514. var facesOfVertices = [];
  16515. var index;
  16516. for (index = 0; index < positions.length; index += 3) {
  16517. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16518. positionVectors.push(vector3);
  16519. facesOfVertices.push([]);
  16520. }
  16521. var facesNormals = [];
  16522. for (index = 0; index < indices.length / 3; index++) {
  16523. var i1 = indices[index * 3];
  16524. var i2 = indices[index * 3 + 1];
  16525. var i3 = indices[index * 3 + 2];
  16526. var p1 = positionVectors[i1];
  16527. var p2 = positionVectors[i2];
  16528. var p3 = positionVectors[i3];
  16529. var p1p2 = p1.subtract(p2);
  16530. var p3p2 = p3.subtract(p2);
  16531. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16532. facesOfVertices[i1].push(index);
  16533. facesOfVertices[i2].push(index);
  16534. facesOfVertices[i3].push(index);
  16535. }
  16536. for (index = 0; index < positionVectors.length; index++) {
  16537. var faces = facesOfVertices[index];
  16538. var normal = BABYLON.Vector3.Zero();
  16539. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16540. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16541. }
  16542. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16543. normals[index * 3] = normal.x;
  16544. normals[index * 3 + 1] = normal.y;
  16545. normals[index * 3 + 2] = normal.z;
  16546. }
  16547. };
  16548. return VertexData;
  16549. })();
  16550. BABYLON.VertexData = VertexData;
  16551. })(BABYLON || (BABYLON = {}));
  16552. var __extends = this.__extends || function (d, b) {
  16553. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16554. function __() { this.constructor = d; }
  16555. __.prototype = b.prototype;
  16556. d.prototype = new __();
  16557. };
  16558. var BABYLON;
  16559. (function (BABYLON) {
  16560. var buildCamera = function (that, name) {
  16561. that._leftCamera.isIntermediate = true;
  16562. that.subCameras.push(that._leftCamera);
  16563. that.subCameras.push(that._rightCamera);
  16564. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16565. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16566. that._anaglyphPostProcess.onApply = function (effect) {
  16567. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16568. };
  16569. that._update();
  16570. };
  16571. var AnaglyphArcRotateCamera = (function (_super) {
  16572. __extends(AnaglyphArcRotateCamera, _super);
  16573. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16574. _super.call(this, name, alpha, beta, radius, target, scene);
  16575. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16576. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16577. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16578. buildCamera(this, name);
  16579. }
  16580. AnaglyphArcRotateCamera.prototype._update = function () {
  16581. this._updateCamera(this._leftCamera);
  16582. this._updateCamera(this._rightCamera);
  16583. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16584. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16585. _super.prototype._update.call(this);
  16586. };
  16587. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16588. camera.beta = this.beta;
  16589. camera.radius = this.radius;
  16590. camera.minZ = this.minZ;
  16591. camera.maxZ = this.maxZ;
  16592. camera.fov = this.fov;
  16593. camera.target = this.target;
  16594. };
  16595. return AnaglyphArcRotateCamera;
  16596. })(BABYLON.ArcRotateCamera);
  16597. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16598. var AnaglyphFreeCamera = (function (_super) {
  16599. __extends(AnaglyphFreeCamera, _super);
  16600. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16601. _super.call(this, name, position, scene);
  16602. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16603. this._transformMatrix = new BABYLON.Matrix();
  16604. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16605. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16606. buildCamera(this, name);
  16607. }
  16608. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16609. var target = this.getTarget();
  16610. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16611. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16612. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16613. };
  16614. AnaglyphFreeCamera.prototype._update = function () {
  16615. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16616. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16617. this._updateCamera(this._leftCamera);
  16618. this._updateCamera(this._rightCamera);
  16619. _super.prototype._update.call(this);
  16620. };
  16621. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16622. camera.minZ = this.minZ;
  16623. camera.maxZ = this.maxZ;
  16624. camera.fov = this.fov;
  16625. camera.viewport = this.viewport;
  16626. camera.setTarget(this.getTarget());
  16627. };
  16628. return AnaglyphFreeCamera;
  16629. })(BABYLON.FreeCamera);
  16630. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16631. })(BABYLON || (BABYLON = {}));
  16632. var __extends = this.__extends || function (d, b) {
  16633. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16634. function __() { this.constructor = d; }
  16635. __.prototype = b.prototype;
  16636. d.prototype = new __();
  16637. };
  16638. var BABYLON;
  16639. (function (BABYLON) {
  16640. var AnaglyphPostProcess = (function (_super) {
  16641. __extends(AnaglyphPostProcess, _super);
  16642. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16643. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16644. }
  16645. return AnaglyphPostProcess;
  16646. })(BABYLON.PostProcess);
  16647. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16648. })(BABYLON || (BABYLON = {}));
  16649. var BABYLON;
  16650. (function (BABYLON) {
  16651. var Tags = (function () {
  16652. function Tags() {
  16653. }
  16654. Tags.EnableFor = function (obj) {
  16655. obj._tags = obj._tags || {};
  16656. obj.hasTags = function () {
  16657. return Tags.HasTags(obj);
  16658. };
  16659. obj.addTags = function (tagsString) {
  16660. return Tags.AddTagsTo(obj, tagsString);
  16661. };
  16662. obj.removeTags = function (tagsString) {
  16663. return Tags.RemoveTagsFrom(obj, tagsString);
  16664. };
  16665. obj.matchesTagsQuery = function (tagsQuery) {
  16666. return Tags.MatchesQuery(obj, tagsQuery);
  16667. };
  16668. };
  16669. Tags.DisableFor = function (obj) {
  16670. delete obj._tags;
  16671. delete obj.hasTags;
  16672. delete obj.addTags;
  16673. delete obj.removeTags;
  16674. delete obj.matchesTagsQuery;
  16675. };
  16676. Tags.HasTags = function (obj) {
  16677. if (!obj._tags) {
  16678. return false;
  16679. }
  16680. return !BABYLON.Tools.IsEmpty(obj._tags);
  16681. };
  16682. Tags.GetTags = function (obj) {
  16683. if (!obj._tags) {
  16684. return null;
  16685. }
  16686. return obj._tags;
  16687. };
  16688. Tags.AddTagsTo = function (obj, tagsString) {
  16689. if (!tagsString) {
  16690. return;
  16691. }
  16692. var tags = tagsString.split(" ");
  16693. for (var t in tags) {
  16694. Tags._AddTagTo(obj, tags[t]);
  16695. }
  16696. };
  16697. Tags._AddTagTo = function (obj, tag) {
  16698. tag = tag.trim();
  16699. if (tag === "" || tag === "true" || tag === "false") {
  16700. return;
  16701. }
  16702. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16703. return;
  16704. }
  16705. Tags.EnableFor(obj);
  16706. obj._tags[tag] = true;
  16707. };
  16708. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16709. if (!Tags.HasTags(obj)) {
  16710. return;
  16711. }
  16712. var tags = tagsString.split(" ");
  16713. for (var t in tags) {
  16714. Tags._RemoveTagFrom(obj, tags[t]);
  16715. }
  16716. };
  16717. Tags._RemoveTagFrom = function (obj, tag) {
  16718. delete obj._tags[tag];
  16719. };
  16720. Tags.MatchesQuery = function (obj, tagsQuery) {
  16721. if (tagsQuery === undefined) {
  16722. return true;
  16723. }
  16724. if (tagsQuery === "") {
  16725. return Tags.HasTags(obj);
  16726. }
  16727. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16728. return Tags.HasTags(obj) && obj._tags[r];
  16729. });
  16730. };
  16731. return Tags;
  16732. })();
  16733. BABYLON.Tags = Tags;
  16734. })(BABYLON || (BABYLON = {}));
  16735. var BABYLON;
  16736. (function (BABYLON) {
  16737. (function (Internals) {
  16738. var AndOrNotEvaluator = (function () {
  16739. function AndOrNotEvaluator() {
  16740. }
  16741. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16742. if (!query.match(/\([^\(\)]*\)/g)) {
  16743. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16744. } else {
  16745. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16746. r = r.slice(1, r.length - 1);
  16747. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16748. });
  16749. }
  16750. if (query === "true") {
  16751. return true;
  16752. }
  16753. if (query === "false") {
  16754. return false;
  16755. }
  16756. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16757. };
  16758. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16759. evaluateCallback = evaluateCallback || (function (r) {
  16760. return r === "true" ? true : false;
  16761. });
  16762. var result;
  16763. var or = parenthesisContent.split("||");
  16764. for (var i in or) {
  16765. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16766. var and = ori.split("&&");
  16767. if (and.length > 1) {
  16768. for (var j = 0; j < and.length; ++j) {
  16769. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16770. if (andj !== "true" && andj !== "false") {
  16771. if (andj[0] === "!") {
  16772. result = !evaluateCallback(andj.substring(1));
  16773. } else {
  16774. result = evaluateCallback(andj);
  16775. }
  16776. } else {
  16777. result = andj === "true" ? true : false;
  16778. }
  16779. if (!result) {
  16780. ori = "false";
  16781. break;
  16782. }
  16783. }
  16784. }
  16785. if (result || ori === "true") {
  16786. result = true;
  16787. break;
  16788. }
  16789. if (ori !== "true" && ori !== "false") {
  16790. if (ori[0] === "!") {
  16791. result = !evaluateCallback(ori.substring(1));
  16792. } else {
  16793. result = evaluateCallback(ori);
  16794. }
  16795. } else {
  16796. result = ori === "true" ? true : false;
  16797. }
  16798. }
  16799. return result ? "true" : "false";
  16800. };
  16801. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16802. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16803. r = r.replace(/[\s]/g, function () {
  16804. return "";
  16805. });
  16806. return r.length % 2 ? "!" : "";
  16807. });
  16808. booleanString = booleanString.trim();
  16809. if (booleanString === "!true") {
  16810. booleanString = "false";
  16811. } else if (booleanString === "!false") {
  16812. booleanString = "true";
  16813. }
  16814. return booleanString;
  16815. };
  16816. return AndOrNotEvaluator;
  16817. })();
  16818. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16819. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16820. var Internals = BABYLON.Internals;
  16821. })(BABYLON || (BABYLON = {}));
  16822. var BABYLON;
  16823. (function (BABYLON) {
  16824. var PostProcessRenderPass = (function () {
  16825. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16826. this._enabled = true;
  16827. this._refCount = 0;
  16828. this._name = name;
  16829. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16830. this.setRenderList(renderList);
  16831. this._renderTexture.onBeforeRender = beforeRender;
  16832. this._renderTexture.onAfterRender = afterRender;
  16833. this._scene = scene;
  16834. }
  16835. PostProcessRenderPass.prototype._incRefCount = function () {
  16836. if (this._refCount === 0) {
  16837. this._scene.customRenderTargets.push(this._renderTexture);
  16838. }
  16839. return ++this._refCount;
  16840. };
  16841. PostProcessRenderPass.prototype._decRefCount = function () {
  16842. this._refCount--;
  16843. if (this._refCount <= 0) {
  16844. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16845. }
  16846. return this._refCount;
  16847. };
  16848. PostProcessRenderPass.prototype._update = function () {
  16849. this.setRenderList(this._renderList);
  16850. };
  16851. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16852. this._renderTexture.renderList = renderList;
  16853. };
  16854. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16855. return this._renderTexture;
  16856. };
  16857. return PostProcessRenderPass;
  16858. })();
  16859. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16860. })(BABYLON || (BABYLON = {}));
  16861. var BABYLON;
  16862. (function (BABYLON) {
  16863. var PostProcessRenderEffect = (function () {
  16864. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16865. this._engine = engine;
  16866. this._name = name;
  16867. this._postProcessType = postProcessType;
  16868. this._ratio = ratio || 1.0;
  16869. this._samplingMode = samplingMode || null;
  16870. this._singleInstance = singleInstance || true;
  16871. this._cameras = [];
  16872. this._postProcesses = [];
  16873. this._indicesForCamera = [];
  16874. this._renderPasses = [];
  16875. this._renderEffectAsPasses = [];
  16876. this.parameters = function (effect) {
  16877. };
  16878. }
  16879. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16880. var postProcess;
  16881. var instance;
  16882. var args = [];
  16883. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16884. for (var i = 0; i < parameters.length; i++) {
  16885. switch (parameters[i]) {
  16886. case "name":
  16887. args[i] = postProcessType.toString();
  16888. break;
  16889. case "ratio":
  16890. args[i] = ratio;
  16891. break;
  16892. case "camera":
  16893. args[i] = null;
  16894. break;
  16895. case "samplingMode":
  16896. args[i] = samplingMode;
  16897. break;
  16898. case "engine":
  16899. args[i] = engine;
  16900. break;
  16901. case "reusable":
  16902. args[i] = true;
  16903. break;
  16904. default:
  16905. args[i] = null;
  16906. break;
  16907. }
  16908. }
  16909. postProcess = function () {
  16910. };
  16911. postProcess.prototype = postProcessType.prototype;
  16912. instance = new postProcess();
  16913. postProcessType.apply(instance, args);
  16914. return instance;
  16915. };
  16916. PostProcessRenderEffect._GetParametersNames = function (func) {
  16917. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16918. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16919. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16920. if (parameters === null)
  16921. parameters = [];
  16922. return parameters;
  16923. };
  16924. PostProcessRenderEffect.prototype._update = function () {
  16925. for (var renderPassName in this._renderPasses) {
  16926. this._renderPasses[renderPassName]._update();
  16927. }
  16928. };
  16929. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16930. this._renderPasses[renderPass._name] = renderPass;
  16931. this._linkParameters();
  16932. };
  16933. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  16934. delete this._renderPasses[renderPass._name];
  16935. this._linkParameters();
  16936. };
  16937. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  16938. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  16939. this._linkParameters();
  16940. };
  16941. PostProcessRenderEffect.prototype.getPass = function (passName) {
  16942. for (var renderPassName in this._renderPasses) {
  16943. if (renderPassName === passName) {
  16944. return this._renderPasses[passName];
  16945. }
  16946. }
  16947. };
  16948. PostProcessRenderEffect.prototype.emptyPasses = function () {
  16949. this._renderPasses.length = 0;
  16950. this._linkParameters();
  16951. };
  16952. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  16953. var cameraKey;
  16954. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16955. for (var i = 0; i < _cam.length; i++) {
  16956. var camera = _cam[i];
  16957. var cameraName = camera.name;
  16958. if (this._singleInstance) {
  16959. cameraKey = 0;
  16960. } else {
  16961. cameraKey = cameraName;
  16962. }
  16963. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  16964. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  16965. if (this._indicesForCamera[cameraName] === null) {
  16966. this._indicesForCamera[cameraName] = [];
  16967. }
  16968. this._indicesForCamera[cameraName].push(index);
  16969. if (this._cameras.indexOf(camera) === -1) {
  16970. this._cameras[cameraName] = camera;
  16971. }
  16972. for (var passName in this._renderPasses) {
  16973. this._renderPasses[passName]._incRefCount();
  16974. }
  16975. }
  16976. this._linkParameters();
  16977. };
  16978. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  16979. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16980. for (var i = 0; i < _cam.length; i++) {
  16981. var camera = _cam[i];
  16982. var cameraName = camera.name;
  16983. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16984. var index = this._cameras.indexOf(cameraName);
  16985. this._indicesForCamera.splice(index, 1);
  16986. this._cameras.splice(index, 1);
  16987. for (var passName in this._renderPasses) {
  16988. this._renderPasses[passName]._decRefCount();
  16989. }
  16990. }
  16991. };
  16992. PostProcessRenderEffect.prototype._enable = function (cameras) {
  16993. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16994. for (var i = 0; i < _cam.length; i++) {
  16995. var camera = _cam[i];
  16996. var cameraName = camera.name;
  16997. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  16998. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  16999. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17000. }
  17001. }
  17002. for (var passName in this._renderPasses) {
  17003. this._renderPasses[passName]._incRefCount();
  17004. }
  17005. }
  17006. };
  17007. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17008. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17009. for (var i = 0; i < _cam.length; i++) {
  17010. var camera = _cam[i];
  17011. var cameraName = camera.Name;
  17012. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17013. for (var passName in this._renderPasses) {
  17014. this._renderPasses[passName]._decRefCount();
  17015. }
  17016. }
  17017. };
  17018. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17019. if (this._singleInstance) {
  17020. return this._postProcesses[0];
  17021. } else {
  17022. return this._postProcesses[camera.name];
  17023. }
  17024. };
  17025. PostProcessRenderEffect.prototype._linkParameters = function () {
  17026. var _this = this;
  17027. for (var index in this._postProcesses) {
  17028. this._postProcesses[index].onApply = function (effect) {
  17029. _this.parameters(effect);
  17030. _this._linkTextures(effect);
  17031. };
  17032. }
  17033. };
  17034. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17035. for (var renderPassName in this._renderPasses) {
  17036. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17037. }
  17038. for (var renderEffectName in this._renderEffectAsPasses) {
  17039. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17040. }
  17041. };
  17042. return PostProcessRenderEffect;
  17043. })();
  17044. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17045. })(BABYLON || (BABYLON = {}));
  17046. var BABYLON;
  17047. (function (BABYLON) {
  17048. var PostProcessRenderPipeline = (function () {
  17049. function PostProcessRenderPipeline(engine, name) {
  17050. this._engine = engine;
  17051. this._name = name;
  17052. this._renderEffects = [];
  17053. this._renderEffectsForIsolatedPass = [];
  17054. this._cameras = [];
  17055. }
  17056. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17057. this._renderEffects[renderEffect._name] = renderEffect;
  17058. };
  17059. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17060. var renderEffects = this._renderEffects[renderEffectName];
  17061. if (!renderEffects) {
  17062. return;
  17063. }
  17064. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17065. };
  17066. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17067. var renderEffects = this._renderEffects[renderEffectName];
  17068. if (!renderEffects) {
  17069. return;
  17070. }
  17071. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17072. };
  17073. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17074. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17075. var indicesToDelete = [];
  17076. for (var i = 0; i < _cam.length; i++) {
  17077. var camera = _cam[i];
  17078. var cameraName = camera.name;
  17079. if (this._cameras.indexOf(camera) === -1) {
  17080. this._cameras[cameraName] = camera;
  17081. } else if (unique) {
  17082. indicesToDelete.push(i);
  17083. }
  17084. }
  17085. for (var i = 0; i < indicesToDelete.length; i++) {
  17086. cameras.splice(indicesToDelete[i], 1);
  17087. }
  17088. for (var renderEffectName in this._renderEffects) {
  17089. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17090. }
  17091. };
  17092. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17093. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17094. for (var renderEffectName in this._renderEffects) {
  17095. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17096. }
  17097. for (var i = 0; i < _cam.length; i++) {
  17098. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17099. }
  17100. };
  17101. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17102. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17103. var pass = null;
  17104. for (var renderEffectName in this._renderEffects) {
  17105. pass = this._renderEffects[renderEffectName].getPass(passName);
  17106. if (pass != null) {
  17107. break;
  17108. }
  17109. }
  17110. if (pass === null) {
  17111. return;
  17112. }
  17113. for (var renderEffectName in this._renderEffects) {
  17114. this._renderEffects[renderEffectName]._disable(_cam);
  17115. }
  17116. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17117. for (var i = 0; i < _cam.length; i++) {
  17118. var camera = _cam[i];
  17119. var cameraName = camera.name;
  17120. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17121. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17122. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17123. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17124. }
  17125. };
  17126. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17127. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17128. for (var i = 0; i < _cam.length; i++) {
  17129. var camera = _cam[i];
  17130. var cameraName = camera.name;
  17131. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17132. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17133. }
  17134. for (var renderEffectName in this._renderEffects) {
  17135. this._renderEffects[renderEffectName]._enable(_cam);
  17136. }
  17137. };
  17138. PostProcessRenderPipeline.prototype._update = function () {
  17139. for (var renderEffectName in this._renderEffects) {
  17140. this._renderEffects[renderEffectName]._update();
  17141. }
  17142. for (var i = 0; i < this._cameras.length; i++) {
  17143. var cameraName = this._cameras[i].name;
  17144. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17145. this._renderEffectsForIsolatedPass[cameraName]._update();
  17146. }
  17147. }
  17148. };
  17149. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17150. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17151. return PostProcessRenderPipeline;
  17152. })();
  17153. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17154. })(BABYLON || (BABYLON = {}));
  17155. var BABYLON;
  17156. (function (BABYLON) {
  17157. var PostProcessRenderPipelineManager = (function () {
  17158. function PostProcessRenderPipelineManager() {
  17159. this._renderPipelines = [];
  17160. }
  17161. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17162. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17163. };
  17164. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17165. var renderPipeline = this._renderPipelines[renderPipelineName];
  17166. if (!renderPipeline) {
  17167. return;
  17168. }
  17169. renderPipeline.attachCameras(cameras, unique);
  17170. };
  17171. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17172. var renderPipeline = this._renderPipelines[renderPipelineName];
  17173. if (!renderPipeline) {
  17174. return;
  17175. }
  17176. renderPipeline.detachCameras(cameras);
  17177. };
  17178. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17179. var renderPipeline = this._renderPipelines[renderPipelineName];
  17180. if (!renderPipeline) {
  17181. return;
  17182. }
  17183. renderPipeline.enableEffect(renderEffectName, cameras);
  17184. };
  17185. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17186. var renderPipeline = this._renderPipelines[renderPipelineName];
  17187. if (!renderPipeline) {
  17188. return;
  17189. }
  17190. renderPipeline.disableEffect(renderEffectName, cameras);
  17191. };
  17192. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17193. var renderPipeline = this._renderPipelines[renderPipelineName];
  17194. if (!renderPipeline) {
  17195. return;
  17196. }
  17197. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17198. };
  17199. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17200. var renderPipeline = this._renderPipelines[renderPipelineName];
  17201. if (!renderPipeline) {
  17202. return;
  17203. }
  17204. renderPipeline.disableDisplayOnlyPass(cameras);
  17205. };
  17206. PostProcessRenderPipelineManager.prototype.update = function () {
  17207. for (var renderPipelineName in this._renderPipelines) {
  17208. this._renderPipelines[renderPipelineName]._update();
  17209. }
  17210. };
  17211. return PostProcessRenderPipelineManager;
  17212. })();
  17213. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17214. })(BABYLON || (BABYLON = {}));
  17215. var __extends = this.__extends || function (d, b) {
  17216. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17217. function __() { this.constructor = d; }
  17218. __.prototype = b.prototype;
  17219. d.prototype = new __();
  17220. };
  17221. var BABYLON;
  17222. (function (BABYLON) {
  17223. var DisplayPassPostProcess = (function (_super) {
  17224. __extends(DisplayPassPostProcess, _super);
  17225. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17226. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17227. }
  17228. return DisplayPassPostProcess;
  17229. })(BABYLON.PostProcess);
  17230. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17231. })(BABYLON || (BABYLON = {}));
  17232. var BABYLON;
  17233. (function (BABYLON) {
  17234. var BoundingBoxRenderer = (function () {
  17235. function BoundingBoxRenderer(scene) {
  17236. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17237. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17238. this.showBackLines = true;
  17239. this.renderList = new BABYLON.SmartArray(32);
  17240. this._scene = scene;
  17241. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17242. attributes: ["position"],
  17243. uniforms: ["worldViewProjection", "color"]
  17244. });
  17245. var engine = this._scene.getEngine();
  17246. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17247. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17248. 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]);
  17249. }
  17250. BoundingBoxRenderer.prototype.reset = function () {
  17251. this.renderList.reset();
  17252. };
  17253. BoundingBoxRenderer.prototype.render = function () {
  17254. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17255. return;
  17256. }
  17257. var engine = this._scene.getEngine();
  17258. engine.setDepthWrite(false);
  17259. this._colorShader._preBind();
  17260. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17261. var boundingBox = this.renderList.data[boundingBoxIndex];
  17262. var min = boundingBox.minimum;
  17263. var max = boundingBox.maximum;
  17264. var diff = max.subtract(min);
  17265. var median = min.add(diff.scale(0.5));
  17266. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17267. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17268. if (this.showBackLines) {
  17269. engine.setDepthFunctionToGreaterOrEqual();
  17270. this._colorShader.setColor4("color", this.backColor.toColor4());
  17271. this._colorShader.bind(worldMatrix);
  17272. engine.draw(false, 0, 24);
  17273. }
  17274. engine.setDepthFunctionToLess();
  17275. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17276. this._colorShader.bind(worldMatrix);
  17277. engine.draw(false, 0, 24);
  17278. }
  17279. this._colorShader.unbind();
  17280. engine.setDepthFunctionToLessOrEqual();
  17281. engine.setDepthWrite(true);
  17282. };
  17283. BoundingBoxRenderer.prototype.dispose = function () {
  17284. this._colorShader.dispose();
  17285. this._vb.dispose();
  17286. this._scene.getEngine()._releaseBuffer(this._ib);
  17287. };
  17288. return BoundingBoxRenderer;
  17289. })();
  17290. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17291. })(BABYLON || (BABYLON = {}));
  17292. /**
  17293. * Based on jsTGALoader - Javascript loader for TGA file
  17294. * By Vincent Thibault
  17295. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17296. */
  17297. var BABYLON;
  17298. (function (BABYLON) {
  17299. (function (Internals) {
  17300. var TGATools = (function () {
  17301. function TGATools() {
  17302. }
  17303. TGATools.GetTGAHeader = function (data) {
  17304. var offset = 0;
  17305. var header = {
  17306. id_length: data[offset++],
  17307. colormap_type: data[offset++],
  17308. image_type: data[offset++],
  17309. colormap_index: data[offset++] | data[offset++] << 8,
  17310. colormap_length: data[offset++] | data[offset++] << 8,
  17311. colormap_size: data[offset++],
  17312. origin: [
  17313. data[offset++] | data[offset++] << 8,
  17314. data[offset++] | data[offset++] << 8
  17315. ],
  17316. width: data[offset++] | data[offset++] << 8,
  17317. height: data[offset++] | data[offset++] << 8,
  17318. pixel_size: data[offset++],
  17319. flags: data[offset++]
  17320. };
  17321. return header;
  17322. };
  17323. TGATools.UploadContent = function (gl, data) {
  17324. if (data.length < 19) {
  17325. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17326. return;
  17327. }
  17328. var offset = 18;
  17329. var header = TGATools.GetTGAHeader(data);
  17330. if (header.id_length + offset > data.length) {
  17331. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17332. return;
  17333. }
  17334. offset += header.id_length;
  17335. var use_rle = false;
  17336. var use_pal = false;
  17337. var use_rgb = false;
  17338. var use_grey = false;
  17339. switch (header.image_type) {
  17340. case TGATools._TYPE_RLE_INDEXED:
  17341. use_rle = true;
  17342. case TGATools._TYPE_INDEXED:
  17343. use_pal = true;
  17344. break;
  17345. case TGATools._TYPE_RLE_RGB:
  17346. use_rle = true;
  17347. case TGATools._TYPE_RGB:
  17348. use_rgb = true;
  17349. break;
  17350. case TGATools._TYPE_RLE_GREY:
  17351. use_rle = true;
  17352. case TGATools._TYPE_GREY:
  17353. use_grey = true;
  17354. break;
  17355. }
  17356. var pixel_data;
  17357. var numAlphaBits = header.flags & 0xf;
  17358. var pixel_size = header.pixel_size >> 3;
  17359. var pixel_total = header.width * header.height * pixel_size;
  17360. var palettes;
  17361. if (use_pal) {
  17362. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17363. }
  17364. if (use_rle) {
  17365. pixel_data = new Uint8Array(pixel_total);
  17366. var c, count, i;
  17367. var localOffset = 0;
  17368. var pixels = new Uint8Array(pixel_size);
  17369. while (offset < pixel_total && localOffset < pixel_total) {
  17370. c = data[offset++];
  17371. count = (c & 0x7f) + 1;
  17372. if (c & 0x80) {
  17373. for (i = 0; i < pixel_size; ++i) {
  17374. pixels[i] = data[offset++];
  17375. }
  17376. for (i = 0; i < count; ++i) {
  17377. pixel_data.set(pixels, localOffset + i * pixel_size);
  17378. }
  17379. localOffset += pixel_size * count;
  17380. } else {
  17381. count *= pixel_size;
  17382. for (i = 0; i < count; ++i) {
  17383. pixel_data[localOffset + i] = data[offset++];
  17384. }
  17385. localOffset += count;
  17386. }
  17387. }
  17388. } else {
  17389. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17390. }
  17391. var x_start, y_start, x_step, y_step, y_end, x_end;
  17392. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17393. default:
  17394. case TGATools._ORIGIN_UL:
  17395. x_start = 0;
  17396. x_step = 1;
  17397. x_end = header.width;
  17398. y_start = 0;
  17399. y_step = 1;
  17400. y_end = header.height;
  17401. break;
  17402. case TGATools._ORIGIN_BL:
  17403. x_start = 0;
  17404. x_step = 1;
  17405. x_end = header.width;
  17406. y_start = header.height - 1;
  17407. y_step = -1;
  17408. y_end = -1;
  17409. break;
  17410. case TGATools._ORIGIN_UR:
  17411. x_start = header.width - 1;
  17412. x_step = -1;
  17413. x_end = -1;
  17414. y_start = 0;
  17415. y_step = 1;
  17416. y_end = header.height;
  17417. break;
  17418. case TGATools._ORIGIN_BR:
  17419. x_start = header.width - 1;
  17420. x_step = -1;
  17421. x_end = -1;
  17422. y_start = header.height - 1;
  17423. y_step = -1;
  17424. y_end = -1;
  17425. break;
  17426. }
  17427. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17428. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17429. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17430. };
  17431. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17432. var image = pixel_data, colormap = palettes;
  17433. var width = header.width, height = header.height;
  17434. var color, i = 0, x, y;
  17435. var imageData = new Uint8Array(width * height * 4);
  17436. for (y = y_start; y !== y_end; y += y_step) {
  17437. for (x = x_start; x !== x_end; x += x_step, i++) {
  17438. color = image[i];
  17439. imageData[(x + width * y) * 4 + 3] = 255;
  17440. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17441. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17442. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17443. }
  17444. }
  17445. return imageData;
  17446. };
  17447. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17448. var image = pixel_data;
  17449. var width = header.width, height = header.height;
  17450. var color, i = 0, x, y;
  17451. var imageData = new Uint8Array(width * height * 4);
  17452. for (y = y_start; y !== y_end; y += y_step) {
  17453. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17454. color = image[i + 0] + (image[i + 1] << 8);
  17455. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17456. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17457. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17458. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17459. }
  17460. }
  17461. return imageData;
  17462. };
  17463. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17464. var image = pixel_data;
  17465. var width = header.width, height = header.height;
  17466. var i = 0, x, y;
  17467. var imageData = new Uint8Array(width * height * 4);
  17468. for (y = y_start; y !== y_end; y += y_step) {
  17469. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17470. imageData[(x + width * y) * 4 + 3] = 255;
  17471. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17472. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17473. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17474. }
  17475. }
  17476. return imageData;
  17477. };
  17478. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17479. var image = pixel_data;
  17480. var width = header.width, height = header.height;
  17481. var i = 0, x, y;
  17482. var imageData = new Uint8Array(width * height * 4);
  17483. for (y = y_start; y !== y_end; y += y_step) {
  17484. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17485. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17486. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17487. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17488. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17489. }
  17490. }
  17491. return imageData;
  17492. };
  17493. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17494. var image = pixel_data;
  17495. var width = header.width, height = header.height;
  17496. var color, i = 0, x, y;
  17497. var imageData = new Uint8Array(width * height * 4);
  17498. for (y = y_start; y !== y_end; y += y_step) {
  17499. for (x = x_start; x !== x_end; x += x_step, i++) {
  17500. color = image[i];
  17501. imageData[(x + width * y) * 4 + 0] = color;
  17502. imageData[(x + width * y) * 4 + 1] = color;
  17503. imageData[(x + width * y) * 4 + 2] = color;
  17504. imageData[(x + width * y) * 4 + 3] = 255;
  17505. }
  17506. }
  17507. return imageData;
  17508. };
  17509. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17510. var image = pixel_data;
  17511. var width = header.width, height = header.height;
  17512. var i = 0, x, y;
  17513. var imageData = new Uint8Array(width * height * 4);
  17514. for (y = y_start; y !== y_end; y += y_step) {
  17515. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17516. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17517. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17518. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17519. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17520. }
  17521. }
  17522. return imageData;
  17523. };
  17524. TGATools._TYPE_NO_DATA = 0;
  17525. TGATools._TYPE_INDEXED = 1;
  17526. TGATools._TYPE_RGB = 2;
  17527. TGATools._TYPE_GREY = 3;
  17528. TGATools._TYPE_RLE_INDEXED = 9;
  17529. TGATools._TYPE_RLE_RGB = 10;
  17530. TGATools._TYPE_RLE_GREY = 11;
  17531. TGATools._ORIGIN_MASK = 0x30;
  17532. TGATools._ORIGIN_SHIFT = 0x04;
  17533. TGATools._ORIGIN_BL = 0x00;
  17534. TGATools._ORIGIN_BR = 0x01;
  17535. TGATools._ORIGIN_UL = 0x02;
  17536. TGATools._ORIGIN_UR = 0x03;
  17537. return TGATools;
  17538. })();
  17539. Internals.TGATools = TGATools;
  17540. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17541. var Internals = BABYLON.Internals;
  17542. })(BABYLON || (BABYLON = {}));
  17543. var BABYLON;
  17544. (function (BABYLON) {
  17545. (function (Internals) {
  17546. var DDS_MAGIC = 0x20534444;
  17547. 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;
  17548. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17549. 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;
  17550. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17551. function FourCCToInt32(value) {
  17552. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17553. }
  17554. function Int32ToFourCC(value) {
  17555. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17556. }
  17557. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17558. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17559. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17560. var headerLengthInt = 31;
  17561. var off_magic = 0;
  17562. var off_size = 1;
  17563. var off_flags = 2;
  17564. var off_height = 3;
  17565. var off_width = 4;
  17566. var off_mipmapCount = 7;
  17567. var off_pfFlags = 20;
  17568. var off_pfFourCC = 21;
  17569. var off_RGBbpp = 22;
  17570. var off_RMask = 23;
  17571. var off_GMask = 24;
  17572. var off_BMask = 25;
  17573. var off_AMask = 26;
  17574. var off_caps1 = 27;
  17575. var off_caps2 = 28;
  17576. ;
  17577. var DDSTools = (function () {
  17578. function DDSTools() {
  17579. }
  17580. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17581. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17582. var mipmapCount = 1;
  17583. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17584. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17585. }
  17586. return {
  17587. width: header[off_width],
  17588. height: header[off_height],
  17589. mipmapCount: mipmapCount,
  17590. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17591. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17592. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17593. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17594. };
  17595. };
  17596. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17597. var byteArray = new Uint8Array(dataLength);
  17598. var srcData = new Uint8Array(arrayBuffer);
  17599. var index = 0;
  17600. for (var y = height - 1; y >= 0; y--) {
  17601. for (var x = 0; x < width; x++) {
  17602. var srcPos = dataOffset + (x + y * width) * 4;
  17603. byteArray[index + 2] = srcData[srcPos];
  17604. byteArray[index + 1] = srcData[srcPos + 1];
  17605. byteArray[index] = srcData[srcPos + 2];
  17606. byteArray[index + 3] = srcData[srcPos + 3];
  17607. index += 4;
  17608. }
  17609. }
  17610. return byteArray;
  17611. };
  17612. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17613. var byteArray = new Uint8Array(dataLength);
  17614. var srcData = new Uint8Array(arrayBuffer);
  17615. var index = 0;
  17616. for (var y = height - 1; y >= 0; y--) {
  17617. for (var x = 0; x < width; x++) {
  17618. var srcPos = dataOffset + (x + y * width) * 3;
  17619. byteArray[index + 2] = srcData[srcPos];
  17620. byteArray[index + 1] = srcData[srcPos + 1];
  17621. byteArray[index] = srcData[srcPos + 2];
  17622. index += 3;
  17623. }
  17624. }
  17625. return byteArray;
  17626. };
  17627. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17628. var byteArray = new Uint8Array(dataLength);
  17629. var srcData = new Uint8Array(arrayBuffer);
  17630. var index = 0;
  17631. for (var y = height - 1; y >= 0; y--) {
  17632. for (var x = 0; x < width; x++) {
  17633. var srcPos = dataOffset + (x + y * width);
  17634. byteArray[index] = srcData[srcPos];
  17635. index++;
  17636. }
  17637. }
  17638. return byteArray;
  17639. };
  17640. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17641. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17642. if (header[off_magic] != DDS_MAGIC) {
  17643. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17644. return;
  17645. }
  17646. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17647. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17648. return;
  17649. }
  17650. if (info.isFourCC) {
  17651. fourCC = header[off_pfFourCC];
  17652. switch (fourCC) {
  17653. case FOURCC_DXT1:
  17654. blockBytes = 8;
  17655. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17656. break;
  17657. case FOURCC_DXT3:
  17658. blockBytes = 16;
  17659. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17660. break;
  17661. case FOURCC_DXT5:
  17662. blockBytes = 16;
  17663. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17664. break;
  17665. default:
  17666. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17667. return;
  17668. }
  17669. }
  17670. mipmapCount = 1;
  17671. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17672. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17673. }
  17674. var bpp = header[off_RGBbpp];
  17675. for (var face = 0; face < faces; face++) {
  17676. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17677. width = header[off_width];
  17678. height = header[off_height];
  17679. dataOffset = header[off_size] + 4;
  17680. for (i = 0; i < mipmapCount; ++i) {
  17681. if (info.isRGB) {
  17682. if (bpp == 24) {
  17683. dataLength = width * height * 3;
  17684. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17685. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17686. } else {
  17687. dataLength = width * height * 4;
  17688. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17689. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17690. }
  17691. } else if (info.isLuminance) {
  17692. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17693. var unpaddedRowSize = width;
  17694. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17695. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17696. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17697. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17698. } else {
  17699. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17700. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17701. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17702. }
  17703. dataOffset += dataLength;
  17704. width *= 0.5;
  17705. height *= 0.5;
  17706. width = Math.max(1.0, width);
  17707. height = Math.max(1.0, height);
  17708. }
  17709. }
  17710. };
  17711. return DDSTools;
  17712. })();
  17713. Internals.DDSTools = DDSTools;
  17714. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17715. var Internals = BABYLON.Internals;
  17716. })(BABYLON || (BABYLON = {}));
  17717. var BABYLON;
  17718. (function (BABYLON) {
  17719. var SmartArray = (function () {
  17720. function SmartArray(capacity) {
  17721. this.length = 0;
  17722. this._duplicateId = 0;
  17723. this.data = new Array(capacity);
  17724. this._id = SmartArray._GlobalId++;
  17725. }
  17726. SmartArray.prototype.push = function (value) {
  17727. this.data[this.length++] = value;
  17728. if (this.length > this.data.length) {
  17729. this.data.length *= 2;
  17730. }
  17731. if (!value.__smartArrayFlags) {
  17732. value.__smartArrayFlags = {};
  17733. }
  17734. value.__smartArrayFlags[this._id] = this._duplicateId;
  17735. };
  17736. SmartArray.prototype.pushNoDuplicate = function (value) {
  17737. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17738. return;
  17739. }
  17740. this.push(value);
  17741. };
  17742. SmartArray.prototype.sort = function (compareFn) {
  17743. this.data.sort(compareFn);
  17744. };
  17745. SmartArray.prototype.reset = function () {
  17746. this.length = 0;
  17747. this._duplicateId++;
  17748. };
  17749. SmartArray.prototype.concat = function (array) {
  17750. if (array.length === 0) {
  17751. return;
  17752. }
  17753. if (this.length + array.length > this.data.length) {
  17754. this.data.length = (this.length + array.length) * 2;
  17755. }
  17756. for (var index = 0; index < array.length; index++) {
  17757. this.data[this.length++] = (array.data || array)[index];
  17758. }
  17759. };
  17760. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17761. if (array.length === 0) {
  17762. return;
  17763. }
  17764. if (this.length + array.length > this.data.length) {
  17765. this.data.length = (this.length + array.length) * 2;
  17766. }
  17767. for (var index = 0; index < array.length; index++) {
  17768. var item = (array.data || array)[index];
  17769. this.pushNoDuplicate(item);
  17770. }
  17771. };
  17772. SmartArray.prototype.indexOf = function (value) {
  17773. var position = this.data.indexOf(value);
  17774. if (position >= this.length) {
  17775. return -1;
  17776. }
  17777. return position;
  17778. };
  17779. SmartArray._GlobalId = 0;
  17780. return SmartArray;
  17781. })();
  17782. BABYLON.SmartArray = SmartArray;
  17783. })(BABYLON || (BABYLON = {}));
  17784. var BABYLON;
  17785. (function (BABYLON) {
  17786. var CannonJSPlugin = (function () {
  17787. function CannonJSPlugin() {
  17788. this._registeredMeshes = [];
  17789. this._physicsMaterials = [];
  17790. this.updateBodyPosition = function (mesh) {
  17791. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17792. var registeredMesh = this._registeredMeshes[index];
  17793. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17794. var body = registeredMesh.body.body;
  17795. var center = mesh.getBoundingInfo().boundingBox.center;
  17796. body.position.set(center.x, center.z, center.y);
  17797. body.quaternion.x = mesh.rotationQuaternion.x;
  17798. body.quaternion.z = mesh.rotationQuaternion.y;
  17799. body.quaternion.y = mesh.rotationQuaternion.z;
  17800. body.quaternion.w = -mesh.rotationQuaternion.w;
  17801. return;
  17802. }
  17803. }
  17804. };
  17805. }
  17806. CannonJSPlugin.prototype.initialize = function (iterations) {
  17807. if (typeof iterations === "undefined") { iterations = 10; }
  17808. this._world = new CANNON.World();
  17809. this._world.broadphase = new CANNON.NaiveBroadphase();
  17810. this._world.solver.iterations = iterations;
  17811. };
  17812. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17813. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17814. };
  17815. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17816. this._world.step(delta);
  17817. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17818. var registeredMesh = this._registeredMeshes[index];
  17819. if (registeredMesh.isChild) {
  17820. continue;
  17821. }
  17822. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17823. var deltaPos = registeredMesh.delta;
  17824. if (deltaPos) {
  17825. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17826. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17827. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17828. } else {
  17829. registeredMesh.mesh.position.x = bodyX;
  17830. registeredMesh.mesh.position.y = bodyZ;
  17831. registeredMesh.mesh.position.z = bodyY;
  17832. }
  17833. if (!registeredMesh.mesh.rotationQuaternion) {
  17834. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17835. }
  17836. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17837. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17838. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17839. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17840. }
  17841. };
  17842. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17843. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17844. };
  17845. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17846. this.unregisterMesh(mesh);
  17847. mesh.computeWorldMatrix(true);
  17848. switch (impostor) {
  17849. case BABYLON.PhysicsEngine.SphereImpostor:
  17850. var bbox = mesh.getBoundingInfo().boundingBox;
  17851. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17852. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17853. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17854. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17855. case BABYLON.PhysicsEngine.BoxImpostor:
  17856. bbox = mesh.getBoundingInfo().boundingBox;
  17857. var min = bbox.minimumWorld;
  17858. var max = bbox.maximumWorld;
  17859. var box = max.subtract(min).scale(0.5);
  17860. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17861. case BABYLON.PhysicsEngine.PlaneImpostor:
  17862. return this._createPlane(mesh, options);
  17863. case BABYLON.PhysicsEngine.MeshImpostor:
  17864. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17865. var rawFaces = mesh.getIndices();
  17866. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17867. }
  17868. return null;
  17869. };
  17870. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17871. var shape = new CANNON.Sphere(radius);
  17872. if (!options) {
  17873. return shape;
  17874. }
  17875. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17876. };
  17877. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17878. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17879. if (!options) {
  17880. return shape;
  17881. }
  17882. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17883. };
  17884. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17885. var shape = new CANNON.Plane();
  17886. if (!options) {
  17887. return shape;
  17888. }
  17889. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17890. };
  17891. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17892. var verts = [], faces = [];
  17893. mesh.computeWorldMatrix(true);
  17894. for (var i = 0; i < rawVerts.length; i += 3) {
  17895. var transformed = BABYLON.Vector3.Zero();
  17896. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17897. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17898. }
  17899. for (var j = 0; j < rawFaces.length; j += 3) {
  17900. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17901. }
  17902. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17903. if (!options) {
  17904. return shape;
  17905. }
  17906. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17907. };
  17908. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17909. var index;
  17910. var mat;
  17911. for (index = 0; index < this._physicsMaterials.length; index++) {
  17912. mat = this._physicsMaterials[index];
  17913. if (mat.friction === friction && mat.restitution === restitution) {
  17914. return mat;
  17915. }
  17916. }
  17917. var currentMat = new CANNON.Material();
  17918. currentMat.friction = friction;
  17919. currentMat.restitution = restitution;
  17920. this._physicsMaterials.push(currentMat);
  17921. for (index = 0; index < this._physicsMaterials.length; index++) {
  17922. mat = this._physicsMaterials[index];
  17923. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17924. contactMaterial.contactEquationStiffness = 1e10;
  17925. contactMaterial.contactEquationRegularizationTime = 10;
  17926. this._world.addContactMaterial(contactMaterial);
  17927. }
  17928. return currentMat;
  17929. };
  17930. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  17931. var initialRotation = null;
  17932. if (mesh.rotationQuaternion) {
  17933. initialRotation = mesh.rotationQuaternion.clone();
  17934. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17935. }
  17936. var bbox = mesh.getBoundingInfo().boundingBox;
  17937. var deltaPosition = mesh.position.subtract(bbox.center);
  17938. var material = this._addMaterial(friction, restitution);
  17939. var body = new CANNON.RigidBody(mass, shape, material);
  17940. if (initialRotation) {
  17941. body.quaternion.x = initialRotation.x;
  17942. body.quaternion.z = initialRotation.y;
  17943. body.quaternion.y = initialRotation.z;
  17944. body.quaternion.w = -initialRotation.w;
  17945. }
  17946. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  17947. this._world.add(body);
  17948. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  17949. return body;
  17950. };
  17951. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17952. var compoundShape = new CANNON.Compound();
  17953. for (var index = 0; index < parts.length; index++) {
  17954. var mesh = parts[index].mesh;
  17955. var shape = this.registerMesh(mesh, parts[index].impostor);
  17956. if (index == 0) {
  17957. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  17958. } else {
  17959. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  17960. }
  17961. }
  17962. var initialMesh = parts[0].mesh;
  17963. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  17964. body.parts = parts;
  17965. return body;
  17966. };
  17967. CannonJSPlugin.prototype._unbindBody = function (body) {
  17968. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17969. var registeredMesh = this._registeredMeshes[index];
  17970. if (registeredMesh.body === body) {
  17971. registeredMesh.body = null;
  17972. registeredMesh.delta = 0;
  17973. }
  17974. }
  17975. };
  17976. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  17977. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17978. var registeredMesh = this._registeredMeshes[index];
  17979. if (registeredMesh.mesh === mesh) {
  17980. if (registeredMesh.body) {
  17981. this._world.remove(registeredMesh.body);
  17982. this._unbindBody(registeredMesh.body);
  17983. }
  17984. this._registeredMeshes.splice(index, 1);
  17985. return;
  17986. }
  17987. }
  17988. };
  17989. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17990. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  17991. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  17992. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17993. var registeredMesh = this._registeredMeshes[index];
  17994. if (registeredMesh.mesh === mesh) {
  17995. registeredMesh.body.applyImpulse(impulse, worldPoint);
  17996. return;
  17997. }
  17998. }
  17999. };
  18000. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18001. var body1 = null, body2 = null;
  18002. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18003. var registeredMesh = this._registeredMeshes[index];
  18004. if (registeredMesh.mesh === mesh1) {
  18005. body1 = registeredMesh.body;
  18006. } else if (registeredMesh.mesh === mesh2) {
  18007. body2 = registeredMesh.body;
  18008. }
  18009. }
  18010. if (!body1 || !body2) {
  18011. return false;
  18012. }
  18013. 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));
  18014. this._world.addConstraint(constraint);
  18015. return true;
  18016. };
  18017. CannonJSPlugin.prototype.dispose = function () {
  18018. while (this._registeredMeshes.length) {
  18019. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18020. }
  18021. };
  18022. CannonJSPlugin.prototype.isSupported = function () {
  18023. return window.CANNON !== undefined;
  18024. };
  18025. return CannonJSPlugin;
  18026. })();
  18027. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18028. })(BABYLON || (BABYLON = {}));
  18029. var __extends = this.__extends || function (d, b) {
  18030. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18031. function __() { this.constructor = d; }
  18032. __.prototype = b.prototype;
  18033. d.prototype = new __();
  18034. };
  18035. var BABYLON;
  18036. (function (BABYLON) {
  18037. var Condition = (function () {
  18038. function Condition(actionManager) {
  18039. this._actionManager = actionManager;
  18040. }
  18041. Condition.prototype.isValid = function () {
  18042. return true;
  18043. };
  18044. Condition.prototype._getProperty = function (propertyPath) {
  18045. return this._actionManager._getProperty(propertyPath);
  18046. };
  18047. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18048. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18049. };
  18050. return Condition;
  18051. })();
  18052. BABYLON.Condition = Condition;
  18053. var ValueCondition = (function (_super) {
  18054. __extends(ValueCondition, _super);
  18055. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18056. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18057. _super.call(this, actionManager);
  18058. this.propertyPath = propertyPath;
  18059. this.value = value;
  18060. this.operator = operator;
  18061. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18062. this._property = this._getProperty(this.propertyPath);
  18063. }
  18064. Object.defineProperty(ValueCondition, "IsEqual", {
  18065. get: function () {
  18066. return ValueCondition._IsEqual;
  18067. },
  18068. enumerable: true,
  18069. configurable: true
  18070. });
  18071. Object.defineProperty(ValueCondition, "IsDifferent", {
  18072. get: function () {
  18073. return ValueCondition._IsDifferent;
  18074. },
  18075. enumerable: true,
  18076. configurable: true
  18077. });
  18078. Object.defineProperty(ValueCondition, "IsGreater", {
  18079. get: function () {
  18080. return ValueCondition._IsGreater;
  18081. },
  18082. enumerable: true,
  18083. configurable: true
  18084. });
  18085. Object.defineProperty(ValueCondition, "IsLesser", {
  18086. get: function () {
  18087. return ValueCondition._IsLesser;
  18088. },
  18089. enumerable: true,
  18090. configurable: true
  18091. });
  18092. ValueCondition.prototype.isValid = function () {
  18093. switch (this.operator) {
  18094. case ValueCondition.IsGreater:
  18095. return this._target[this._property] > this.value;
  18096. case ValueCondition.IsLesser:
  18097. return this._target[this._property] < this.value;
  18098. case ValueCondition.IsEqual:
  18099. case ValueCondition.IsDifferent:
  18100. var check;
  18101. if (this.value.equals) {
  18102. check = this.value.equals(this._target[this._property]);
  18103. } else {
  18104. check = this.value === this._target[this._property];
  18105. }
  18106. return this.operator === ValueCondition.IsEqual ? check : !check;
  18107. }
  18108. return false;
  18109. };
  18110. ValueCondition._IsEqual = 0;
  18111. ValueCondition._IsDifferent = 1;
  18112. ValueCondition._IsGreater = 2;
  18113. ValueCondition._IsLesser = 3;
  18114. return ValueCondition;
  18115. })(Condition);
  18116. BABYLON.ValueCondition = ValueCondition;
  18117. var PredicateCondition = (function (_super) {
  18118. __extends(PredicateCondition, _super);
  18119. function PredicateCondition(actionManager, predicate) {
  18120. _super.call(this, actionManager);
  18121. this.predicate = predicate;
  18122. }
  18123. PredicateCondition.prototype.isValid = function () {
  18124. return this.predicate();
  18125. };
  18126. return PredicateCondition;
  18127. })(Condition);
  18128. BABYLON.PredicateCondition = PredicateCondition;
  18129. var StateCondition = (function (_super) {
  18130. __extends(StateCondition, _super);
  18131. function StateCondition(actionManager, target, value) {
  18132. _super.call(this, actionManager);
  18133. this.value = value;
  18134. this._target = target;
  18135. }
  18136. StateCondition.prototype.isValid = function () {
  18137. return this._target.state === this.value;
  18138. };
  18139. return StateCondition;
  18140. })(Condition);
  18141. BABYLON.StateCondition = StateCondition;
  18142. })(BABYLON || (BABYLON = {}));
  18143. var BABYLON;
  18144. (function (BABYLON) {
  18145. var Action = (function () {
  18146. function Action(triggerOptions, condition) {
  18147. this.triggerOptions = triggerOptions;
  18148. if (triggerOptions.parameter) {
  18149. this.trigger = triggerOptions.trigger;
  18150. this._triggerParameter = triggerOptions.parameter;
  18151. } else {
  18152. this.trigger = triggerOptions;
  18153. }
  18154. this._nextActiveAction = this;
  18155. this._condition = condition;
  18156. }
  18157. Action.prototype._prepare = function () {
  18158. };
  18159. Action.prototype.getTriggerParameter = function () {
  18160. return this._triggerParameter;
  18161. };
  18162. Action.prototype._executeCurrent = function (evt) {
  18163. if (this._condition) {
  18164. var currentRenderId = this._actionManager.getScene().getRenderId();
  18165. if (this._condition._evaluationId === currentRenderId) {
  18166. if (!this._condition._currentResult) {
  18167. return;
  18168. }
  18169. } else {
  18170. this._condition._evaluationId = currentRenderId;
  18171. if (!this._condition.isValid()) {
  18172. this._condition._currentResult = false;
  18173. return;
  18174. }
  18175. this._condition._currentResult = true;
  18176. }
  18177. }
  18178. this._nextActiveAction.execute(evt);
  18179. if (this._nextActiveAction._child) {
  18180. this._nextActiveAction = this._nextActiveAction._child;
  18181. } else {
  18182. this._nextActiveAction = this;
  18183. }
  18184. };
  18185. Action.prototype.execute = function (evt) {
  18186. };
  18187. Action.prototype.then = function (action) {
  18188. this._child = action;
  18189. action._actionManager = this._actionManager;
  18190. action._prepare();
  18191. return action;
  18192. };
  18193. Action.prototype._getProperty = function (propertyPath) {
  18194. return this._actionManager._getProperty(propertyPath);
  18195. };
  18196. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18197. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18198. };
  18199. return Action;
  18200. })();
  18201. BABYLON.Action = Action;
  18202. })(BABYLON || (BABYLON = {}));
  18203. var BABYLON;
  18204. (function (BABYLON) {
  18205. var ActionEvent = (function () {
  18206. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18207. this.source = source;
  18208. this.pointerX = pointerX;
  18209. this.pointerY = pointerY;
  18210. this.meshUnderPointer = meshUnderPointer;
  18211. this.sourceEvent = sourceEvent;
  18212. }
  18213. ActionEvent.CreateNew = function (source) {
  18214. var scene = source.getScene();
  18215. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18216. };
  18217. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18218. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18219. };
  18220. return ActionEvent;
  18221. })();
  18222. BABYLON.ActionEvent = ActionEvent;
  18223. var ActionManager = (function () {
  18224. function ActionManager(scene) {
  18225. this.actions = new Array();
  18226. this._scene = scene;
  18227. scene._actionManagers.push(this);
  18228. }
  18229. Object.defineProperty(ActionManager, "NothingTrigger", {
  18230. get: function () {
  18231. return ActionManager._NothingTrigger;
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18237. get: function () {
  18238. return ActionManager._OnPickTrigger;
  18239. },
  18240. enumerable: true,
  18241. configurable: true
  18242. });
  18243. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18244. get: function () {
  18245. return ActionManager._OnLeftPickTrigger;
  18246. },
  18247. enumerable: true,
  18248. configurable: true
  18249. });
  18250. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18251. get: function () {
  18252. return ActionManager._OnRightPickTrigger;
  18253. },
  18254. enumerable: true,
  18255. configurable: true
  18256. });
  18257. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18258. get: function () {
  18259. return ActionManager._OnCenterPickTrigger;
  18260. },
  18261. enumerable: true,
  18262. configurable: true
  18263. });
  18264. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18265. get: function () {
  18266. return ActionManager._OnPointerOverTrigger;
  18267. },
  18268. enumerable: true,
  18269. configurable: true
  18270. });
  18271. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18272. get: function () {
  18273. return ActionManager._OnPointerOutTrigger;
  18274. },
  18275. enumerable: true,
  18276. configurable: true
  18277. });
  18278. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18279. get: function () {
  18280. return ActionManager._OnEveryFrameTrigger;
  18281. },
  18282. enumerable: true,
  18283. configurable: true
  18284. });
  18285. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18286. get: function () {
  18287. return ActionManager._OnIntersectionEnterTrigger;
  18288. },
  18289. enumerable: true,
  18290. configurable: true
  18291. });
  18292. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18293. get: function () {
  18294. return ActionManager._OnIntersectionExitTrigger;
  18295. },
  18296. enumerable: true,
  18297. configurable: true
  18298. });
  18299. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18300. get: function () {
  18301. return ActionManager._OnKeyDownTrigger;
  18302. },
  18303. enumerable: true,
  18304. configurable: true
  18305. });
  18306. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18307. get: function () {
  18308. return ActionManager._OnKeyUpTrigger;
  18309. },
  18310. enumerable: true,
  18311. configurable: true
  18312. });
  18313. ActionManager.prototype.dispose = function () {
  18314. var index = this._scene._actionManagers.indexOf(this);
  18315. if (index > -1) {
  18316. this._scene._actionManagers.splice(index, 1);
  18317. }
  18318. };
  18319. ActionManager.prototype.getScene = function () {
  18320. return this._scene;
  18321. };
  18322. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18323. for (var index = 0; index < this.actions.length; index++) {
  18324. var action = this.actions[index];
  18325. if (triggers.indexOf(action.trigger) > -1) {
  18326. return true;
  18327. }
  18328. }
  18329. return false;
  18330. };
  18331. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18332. get: function () {
  18333. for (var index = 0; index < this.actions.length; index++) {
  18334. var action = this.actions[index];
  18335. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18336. return true;
  18337. }
  18338. }
  18339. return false;
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18345. get: function () {
  18346. for (var index = 0; index < this.actions.length; index++) {
  18347. var action = this.actions[index];
  18348. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18349. return true;
  18350. }
  18351. }
  18352. return false;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. ActionManager.prototype.registerAction = function (action) {
  18358. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18359. if (this.getScene().actionManager !== this) {
  18360. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18361. return null;
  18362. }
  18363. }
  18364. this.actions.push(action);
  18365. action._actionManager = this;
  18366. action._prepare();
  18367. return action;
  18368. };
  18369. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18370. for (var index = 0; index < this.actions.length; index++) {
  18371. var action = this.actions[index];
  18372. if (action.trigger === trigger) {
  18373. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18374. var parameter = action.getTriggerParameter();
  18375. if (parameter) {
  18376. if (evt.sourceEvent.key !== parameter) {
  18377. continue;
  18378. }
  18379. }
  18380. }
  18381. action._executeCurrent(evt);
  18382. }
  18383. }
  18384. };
  18385. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18386. var properties = propertyPath.split(".");
  18387. for (var index = 0; index < properties.length - 1; index++) {
  18388. target = target[properties[index]];
  18389. }
  18390. return target;
  18391. };
  18392. ActionManager.prototype._getProperty = function (propertyPath) {
  18393. var properties = propertyPath.split(".");
  18394. return properties[properties.length - 1];
  18395. };
  18396. ActionManager._NothingTrigger = 0;
  18397. ActionManager._OnPickTrigger = 1;
  18398. ActionManager._OnLeftPickTrigger = 2;
  18399. ActionManager._OnRightPickTrigger = 3;
  18400. ActionManager._OnCenterPickTrigger = 4;
  18401. ActionManager._OnPointerOverTrigger = 5;
  18402. ActionManager._OnPointerOutTrigger = 6;
  18403. ActionManager._OnEveryFrameTrigger = 7;
  18404. ActionManager._OnIntersectionEnterTrigger = 8;
  18405. ActionManager._OnIntersectionExitTrigger = 9;
  18406. ActionManager._OnKeyDownTrigger = 10;
  18407. ActionManager._OnKeyUpTrigger = 11;
  18408. return ActionManager;
  18409. })();
  18410. BABYLON.ActionManager = ActionManager;
  18411. })(BABYLON || (BABYLON = {}));
  18412. var __extends = this.__extends || function (d, b) {
  18413. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18414. function __() { this.constructor = d; }
  18415. __.prototype = b.prototype;
  18416. d.prototype = new __();
  18417. };
  18418. var BABYLON;
  18419. (function (BABYLON) {
  18420. var InterpolateValueAction = (function (_super) {
  18421. __extends(InterpolateValueAction, _super);
  18422. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18423. if (typeof duration === "undefined") { duration = 1000; }
  18424. _super.call(this, triggerOptions, condition);
  18425. this.propertyPath = propertyPath;
  18426. this.value = value;
  18427. this.duration = duration;
  18428. this.stopOtherAnimations = stopOtherAnimations;
  18429. this._target = target;
  18430. }
  18431. InterpolateValueAction.prototype._prepare = function () {
  18432. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18433. this._property = this._getProperty(this.propertyPath);
  18434. };
  18435. InterpolateValueAction.prototype.execute = function () {
  18436. var scene = this._actionManager.getScene();
  18437. var keys = [
  18438. {
  18439. frame: 0,
  18440. value: this._target[this._property]
  18441. }, {
  18442. frame: 100,
  18443. value: this.value
  18444. }
  18445. ];
  18446. var dataType;
  18447. if (typeof this.value === "number") {
  18448. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18449. } else if (this.value instanceof BABYLON.Color3) {
  18450. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18451. } else if (this.value instanceof BABYLON.Vector3) {
  18452. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18453. } else if (this.value instanceof BABYLON.Matrix) {
  18454. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18455. } else if (this.value instanceof BABYLON.Quaternion) {
  18456. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18457. } else {
  18458. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18459. return;
  18460. }
  18461. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18462. animation.setKeys(keys);
  18463. if (this.stopOtherAnimations) {
  18464. scene.stopAnimation(this._target);
  18465. }
  18466. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18467. };
  18468. return InterpolateValueAction;
  18469. })(BABYLON.Action);
  18470. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18471. })(BABYLON || (BABYLON = {}));
  18472. var __extends = this.__extends || function (d, b) {
  18473. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18474. function __() { this.constructor = d; }
  18475. __.prototype = b.prototype;
  18476. d.prototype = new __();
  18477. };
  18478. var BABYLON;
  18479. (function (BABYLON) {
  18480. var SwitchBooleanAction = (function (_super) {
  18481. __extends(SwitchBooleanAction, _super);
  18482. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18483. _super.call(this, triggerOptions, condition);
  18484. this.propertyPath = propertyPath;
  18485. this._target = target;
  18486. }
  18487. SwitchBooleanAction.prototype._prepare = function () {
  18488. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18489. this._property = this._getProperty(this.propertyPath);
  18490. };
  18491. SwitchBooleanAction.prototype.execute = function () {
  18492. this._target[this._property] = !this._target[this._property];
  18493. };
  18494. return SwitchBooleanAction;
  18495. })(BABYLON.Action);
  18496. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18497. var SetStateAction = (function (_super) {
  18498. __extends(SetStateAction, _super);
  18499. function SetStateAction(triggerOptions, target, value, condition) {
  18500. _super.call(this, triggerOptions, condition);
  18501. this.value = value;
  18502. this._target = target;
  18503. }
  18504. SetStateAction.prototype.execute = function () {
  18505. this._target.state = this.value;
  18506. };
  18507. return SetStateAction;
  18508. })(BABYLON.Action);
  18509. BABYLON.SetStateAction = SetStateAction;
  18510. var SetValueAction = (function (_super) {
  18511. __extends(SetValueAction, _super);
  18512. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18513. _super.call(this, triggerOptions, condition);
  18514. this.propertyPath = propertyPath;
  18515. this.value = value;
  18516. this._target = target;
  18517. }
  18518. SetValueAction.prototype._prepare = function () {
  18519. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18520. this._property = this._getProperty(this.propertyPath);
  18521. };
  18522. SetValueAction.prototype.execute = function () {
  18523. this._target[this._property] = this.value;
  18524. };
  18525. return SetValueAction;
  18526. })(BABYLON.Action);
  18527. BABYLON.SetValueAction = SetValueAction;
  18528. var IncrementValueAction = (function (_super) {
  18529. __extends(IncrementValueAction, _super);
  18530. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18531. _super.call(this, triggerOptions, condition);
  18532. this.propertyPath = propertyPath;
  18533. this.value = value;
  18534. this._target = target;
  18535. }
  18536. IncrementValueAction.prototype._prepare = function () {
  18537. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18538. this._property = this._getProperty(this.propertyPath);
  18539. if (typeof this._target[this._property] !== "number") {
  18540. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18541. }
  18542. };
  18543. IncrementValueAction.prototype.execute = function () {
  18544. this._target[this._property] += this.value;
  18545. };
  18546. return IncrementValueAction;
  18547. })(BABYLON.Action);
  18548. BABYLON.IncrementValueAction = IncrementValueAction;
  18549. var PlayAnimationAction = (function (_super) {
  18550. __extends(PlayAnimationAction, _super);
  18551. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18552. _super.call(this, triggerOptions, condition);
  18553. this.from = from;
  18554. this.to = to;
  18555. this.loop = loop;
  18556. this._target = target;
  18557. }
  18558. PlayAnimationAction.prototype._prepare = function () {
  18559. };
  18560. PlayAnimationAction.prototype.execute = function () {
  18561. var scene = this._actionManager.getScene();
  18562. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18563. };
  18564. return PlayAnimationAction;
  18565. })(BABYLON.Action);
  18566. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18567. var StopAnimationAction = (function (_super) {
  18568. __extends(StopAnimationAction, _super);
  18569. function StopAnimationAction(triggerOptions, target, condition) {
  18570. _super.call(this, triggerOptions, condition);
  18571. this._target = target;
  18572. }
  18573. StopAnimationAction.prototype._prepare = function () {
  18574. };
  18575. StopAnimationAction.prototype.execute = function () {
  18576. var scene = this._actionManager.getScene();
  18577. scene.stopAnimation(this._target);
  18578. };
  18579. return StopAnimationAction;
  18580. })(BABYLON.Action);
  18581. BABYLON.StopAnimationAction = StopAnimationAction;
  18582. var DoNothingAction = (function (_super) {
  18583. __extends(DoNothingAction, _super);
  18584. function DoNothingAction(triggerOptions, condition) {
  18585. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18586. _super.call(this, triggerOptions, condition);
  18587. }
  18588. DoNothingAction.prototype.execute = function () {
  18589. };
  18590. return DoNothingAction;
  18591. })(BABYLON.Action);
  18592. BABYLON.DoNothingAction = DoNothingAction;
  18593. var CombineAction = (function (_super) {
  18594. __extends(CombineAction, _super);
  18595. function CombineAction(triggerOptions, children, condition) {
  18596. _super.call(this, triggerOptions, condition);
  18597. this.children = children;
  18598. }
  18599. CombineAction.prototype._prepare = function () {
  18600. for (var index = 0; index < this.children.length; index++) {
  18601. this.children[index]._actionManager = this._actionManager;
  18602. this.children[index]._prepare();
  18603. }
  18604. };
  18605. CombineAction.prototype.execute = function (evt) {
  18606. for (var index = 0; index < this.children.length; index++) {
  18607. this.children[index].execute(evt);
  18608. }
  18609. };
  18610. return CombineAction;
  18611. })(BABYLON.Action);
  18612. BABYLON.CombineAction = CombineAction;
  18613. var ExecuteCodeAction = (function (_super) {
  18614. __extends(ExecuteCodeAction, _super);
  18615. function ExecuteCodeAction(triggerOptions, func, condition) {
  18616. _super.call(this, triggerOptions, condition);
  18617. this.func = func;
  18618. }
  18619. ExecuteCodeAction.prototype.execute = function (evt) {
  18620. this.func(evt);
  18621. };
  18622. return ExecuteCodeAction;
  18623. })(BABYLON.Action);
  18624. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18625. var SetParentAction = (function (_super) {
  18626. __extends(SetParentAction, _super);
  18627. function SetParentAction(triggerOptions, target, parent, condition) {
  18628. _super.call(this, triggerOptions, condition);
  18629. this._target = target;
  18630. this._parent = parent;
  18631. }
  18632. SetParentAction.prototype._prepare = function () {
  18633. };
  18634. SetParentAction.prototype.execute = function () {
  18635. if (this._target.parent === this._parent) {
  18636. return;
  18637. }
  18638. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18639. invertParentWorldMatrix.invert();
  18640. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18641. this._target.parent = this._parent;
  18642. };
  18643. return SetParentAction;
  18644. })(BABYLON.Action);
  18645. BABYLON.SetParentAction = SetParentAction;
  18646. })(BABYLON || (BABYLON = {}));
  18647. var __extends = this.__extends || function (d, b) {
  18648. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18649. function __() { this.constructor = d; }
  18650. __.prototype = b.prototype;
  18651. d.prototype = new __();
  18652. };
  18653. var BABYLON;
  18654. (function (BABYLON) {
  18655. var Geometry = (function () {
  18656. function Geometry(id, scene, vertexData, updatable, mesh) {
  18657. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18658. this._totalVertices = 0;
  18659. this._indices = [];
  18660. this.id = id;
  18661. this._engine = scene.getEngine();
  18662. this._meshes = [];
  18663. this._scene = scene;
  18664. if (vertexData) {
  18665. this.setAllVerticesData(vertexData, updatable);
  18666. } else {
  18667. this._totalVertices = 0;
  18668. this._indices = [];
  18669. }
  18670. if (mesh) {
  18671. this.applyToMesh(mesh);
  18672. }
  18673. }
  18674. Geometry.prototype.getScene = function () {
  18675. return this._scene;
  18676. };
  18677. Geometry.prototype.getEngine = function () {
  18678. return this._engine;
  18679. };
  18680. Geometry.prototype.isReady = function () {
  18681. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18682. };
  18683. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18684. vertexData.applyToGeometry(this, updatable);
  18685. };
  18686. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18687. this._vertexBuffers = this._vertexBuffers || {};
  18688. if (this._vertexBuffers[kind]) {
  18689. this._vertexBuffers[kind].dispose();
  18690. }
  18691. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18692. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18693. var stride = this._vertexBuffers[kind].getStrideSize();
  18694. this._totalVertices = data.length / stride;
  18695. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18696. var meshes = this._meshes;
  18697. var numOfMeshes = meshes.length;
  18698. for (var index = 0; index < numOfMeshes; index++) {
  18699. var mesh = meshes[index];
  18700. mesh._resetPointsArrayCache();
  18701. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18702. mesh._createGlobalSubMesh();
  18703. mesh.computeWorldMatrix(true);
  18704. }
  18705. }
  18706. };
  18707. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18708. var vertexBuffer = this.getVertexBuffer(kind);
  18709. if (!vertexBuffer) {
  18710. return;
  18711. }
  18712. vertexBuffer.update(data);
  18713. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18714. var extend;
  18715. if (updateExtends) {
  18716. var stride = vertexBuffer.getStrideSize();
  18717. this._totalVertices = data.length / stride;
  18718. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18719. }
  18720. var meshes = this._meshes;
  18721. var numOfMeshes = meshes.length;
  18722. for (var index = 0; index < numOfMeshes; index++) {
  18723. var mesh = meshes[index];
  18724. mesh._resetPointsArrayCache();
  18725. if (updateExtends) {
  18726. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18727. }
  18728. }
  18729. }
  18730. };
  18731. Geometry.prototype.getTotalVertices = function () {
  18732. if (!this.isReady()) {
  18733. return 0;
  18734. }
  18735. return this._totalVertices;
  18736. };
  18737. Geometry.prototype.getVerticesData = function (kind) {
  18738. var vertexBuffer = this.getVertexBuffer(kind);
  18739. if (!vertexBuffer) {
  18740. return null;
  18741. }
  18742. return vertexBuffer.getData();
  18743. };
  18744. Geometry.prototype.getVertexBuffer = function (kind) {
  18745. if (!this.isReady()) {
  18746. return null;
  18747. }
  18748. return this._vertexBuffers[kind];
  18749. };
  18750. Geometry.prototype.getVertexBuffers = function () {
  18751. if (!this.isReady()) {
  18752. return null;
  18753. }
  18754. return this._vertexBuffers;
  18755. };
  18756. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18757. if (!this._vertexBuffers) {
  18758. if (this._delayInfo) {
  18759. return this._delayInfo.indexOf(kind) !== -1;
  18760. }
  18761. return false;
  18762. }
  18763. return this._vertexBuffers[kind] !== undefined;
  18764. };
  18765. Geometry.prototype.getVerticesDataKinds = function () {
  18766. var result = [];
  18767. if (!this._vertexBuffers && this._delayInfo) {
  18768. for (var kind in this._delayInfo) {
  18769. result.push(kind);
  18770. }
  18771. } else {
  18772. for (kind in this._vertexBuffers) {
  18773. result.push(kind);
  18774. }
  18775. }
  18776. return result;
  18777. };
  18778. Geometry.prototype.setIndices = function (indices) {
  18779. if (this._indexBuffer) {
  18780. this._engine._releaseBuffer(this._indexBuffer);
  18781. }
  18782. this._indices = indices;
  18783. if (this._meshes.length !== 0 && this._indices) {
  18784. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18785. }
  18786. var meshes = this._meshes;
  18787. var numOfMeshes = meshes.length;
  18788. for (var index = 0; index < numOfMeshes; index++) {
  18789. meshes[index]._createGlobalSubMesh();
  18790. }
  18791. };
  18792. Geometry.prototype.getTotalIndices = function () {
  18793. if (!this.isReady()) {
  18794. return 0;
  18795. }
  18796. return this._indices.length;
  18797. };
  18798. Geometry.prototype.getIndices = function () {
  18799. if (!this.isReady()) {
  18800. return null;
  18801. }
  18802. return this._indices;
  18803. };
  18804. Geometry.prototype.getIndexBuffer = function () {
  18805. if (!this.isReady()) {
  18806. return null;
  18807. }
  18808. return this._indexBuffer;
  18809. };
  18810. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18811. var meshes = this._meshes;
  18812. var index = meshes.indexOf(mesh);
  18813. if (index === -1) {
  18814. return;
  18815. }
  18816. for (var kind in this._vertexBuffers) {
  18817. this._vertexBuffers[kind].dispose();
  18818. }
  18819. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18820. this._indexBuffer = null;
  18821. }
  18822. meshes.splice(index, 1);
  18823. mesh._geometry = null;
  18824. if (meshes.length == 0 && shouldDispose) {
  18825. this.dispose();
  18826. }
  18827. };
  18828. Geometry.prototype.applyToMesh = function (mesh) {
  18829. if (mesh._geometry === this) {
  18830. return;
  18831. }
  18832. var previousGeometry = mesh._geometry;
  18833. if (previousGeometry) {
  18834. previousGeometry.releaseForMesh(mesh);
  18835. }
  18836. var meshes = this._meshes;
  18837. mesh._geometry = this;
  18838. this._scene.pushGeometry(this);
  18839. meshes.push(mesh);
  18840. if (this.isReady()) {
  18841. this._applyToMesh(mesh);
  18842. } else {
  18843. mesh._boundingInfo = this._boundingInfo;
  18844. }
  18845. };
  18846. Geometry.prototype._applyToMesh = function (mesh) {
  18847. var numOfMeshes = this._meshes.length;
  18848. for (var kind in this._vertexBuffers) {
  18849. if (numOfMeshes === 1) {
  18850. this._vertexBuffers[kind].create();
  18851. }
  18852. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18853. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18854. mesh._resetPointsArrayCache();
  18855. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18856. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18857. mesh._createGlobalSubMesh();
  18858. }
  18859. }
  18860. if (numOfMeshes === 1 && this._indices) {
  18861. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18862. }
  18863. if (this._indexBuffer) {
  18864. this._indexBuffer.references = numOfMeshes;
  18865. }
  18866. };
  18867. Geometry.prototype.load = function (scene, onLoaded) {
  18868. var _this = this;
  18869. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18870. return;
  18871. }
  18872. if (this.isReady()) {
  18873. if (onLoaded) {
  18874. onLoaded();
  18875. }
  18876. return;
  18877. }
  18878. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18879. scene._addPendingData(this);
  18880. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18881. _this._delayLoadingFunction(JSON.parse(data), _this);
  18882. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18883. _this._delayInfo = [];
  18884. scene._removePendingData(_this);
  18885. var meshes = _this._meshes;
  18886. var numOfMeshes = meshes.length;
  18887. for (var index = 0; index < numOfMeshes; index++) {
  18888. _this._applyToMesh(meshes[index]);
  18889. }
  18890. if (onLoaded) {
  18891. onLoaded();
  18892. }
  18893. }, function () {
  18894. }, scene.database);
  18895. };
  18896. Geometry.prototype.dispose = function () {
  18897. var meshes = this._meshes;
  18898. var numOfMeshes = meshes.length;
  18899. for (var index = 0; index < numOfMeshes; index++) {
  18900. this.releaseForMesh(meshes[index]);
  18901. }
  18902. this._meshes = [];
  18903. for (var kind in this._vertexBuffers) {
  18904. this._vertexBuffers[kind].dispose();
  18905. }
  18906. this._vertexBuffers = [];
  18907. this._totalVertices = 0;
  18908. if (this._indexBuffer) {
  18909. this._engine._releaseBuffer(this._indexBuffer);
  18910. }
  18911. this._indexBuffer = null;
  18912. this._indices = [];
  18913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18914. this.delayLoadingFile = null;
  18915. this._delayLoadingFunction = null;
  18916. this._delayInfo = [];
  18917. this._boundingInfo = null;
  18918. var geometries = this._scene.getGeometries();
  18919. index = geometries.indexOf(this);
  18920. if (index > -1) {
  18921. geometries.splice(index, 1);
  18922. }
  18923. };
  18924. Geometry.prototype.copy = function (id) {
  18925. var vertexData = new BABYLON.VertexData();
  18926. vertexData.indices = [];
  18927. var indices = this.getIndices();
  18928. for (var index = 0; index < indices.length; index++) {
  18929. vertexData.indices.push(indices[index]);
  18930. }
  18931. var updatable = false;
  18932. var stopChecking = false;
  18933. for (var kind in this._vertexBuffers) {
  18934. vertexData.set(this.getVerticesData(kind), kind);
  18935. if (!stopChecking) {
  18936. updatable = this.getVertexBuffer(kind).isUpdatable();
  18937. stopChecking = !updatable;
  18938. }
  18939. }
  18940. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  18941. geometry.delayLoadState = this.delayLoadState;
  18942. geometry.delayLoadingFile = this.delayLoadingFile;
  18943. geometry._delayLoadingFunction = this._delayLoadingFunction;
  18944. for (kind in this._delayInfo) {
  18945. geometry._delayInfo = geometry._delayInfo || [];
  18946. geometry._delayInfo.push(kind);
  18947. }
  18948. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  18949. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18950. return geometry;
  18951. };
  18952. Geometry.ExtractFromMesh = function (mesh, id) {
  18953. var geometry = mesh._geometry;
  18954. if (!geometry) {
  18955. return null;
  18956. }
  18957. return geometry.copy(id);
  18958. };
  18959. Geometry.RandomId = function () {
  18960. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  18961. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  18962. return v.toString(16);
  18963. });
  18964. };
  18965. return Geometry;
  18966. })();
  18967. BABYLON.Geometry = Geometry;
  18968. (function (Geometry) {
  18969. (function (Primitives) {
  18970. var _Primitive = (function (_super) {
  18971. __extends(_Primitive, _super);
  18972. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  18973. this._beingRegenerated = true;
  18974. this._canBeRegenerated = canBeRegenerated;
  18975. _super.call(this, id, scene, vertexData, false, mesh);
  18976. this._beingRegenerated = false;
  18977. }
  18978. _Primitive.prototype.canBeRegenerated = function () {
  18979. return this._canBeRegenerated;
  18980. };
  18981. _Primitive.prototype.regenerate = function () {
  18982. if (!this._canBeRegenerated) {
  18983. return;
  18984. }
  18985. this._beingRegenerated = true;
  18986. this.setAllVerticesData(this._regenerateVertexData(), false);
  18987. this._beingRegenerated = false;
  18988. };
  18989. _Primitive.prototype.asNewGeometry = function (id) {
  18990. return _super.prototype.copy.call(this, id);
  18991. };
  18992. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  18993. if (!this._beingRegenerated) {
  18994. return;
  18995. }
  18996. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  18997. };
  18998. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  18999. if (!this._beingRegenerated) {
  19000. return;
  19001. }
  19002. _super.prototype.setVerticesData.call(this, kind, data, false);
  19003. };
  19004. _Primitive.prototype._regenerateVertexData = function () {
  19005. throw new Error("Abstract method");
  19006. };
  19007. _Primitive.prototype.copy = function (id) {
  19008. throw new Error("Must be overriden in sub-classes.");
  19009. };
  19010. return _Primitive;
  19011. })(Geometry);
  19012. Primitives._Primitive = _Primitive;
  19013. var Box = (function (_super) {
  19014. __extends(Box, _super);
  19015. function Box(id, scene, size, canBeRegenerated, mesh) {
  19016. this.size = size;
  19017. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19018. }
  19019. Box.prototype._regenerateVertexData = function () {
  19020. return BABYLON.VertexData.CreateBox(this.size);
  19021. };
  19022. Box.prototype.copy = function (id) {
  19023. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19024. };
  19025. return Box;
  19026. })(_Primitive);
  19027. Primitives.Box = Box;
  19028. var Sphere = (function (_super) {
  19029. __extends(Sphere, _super);
  19030. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19031. this.segments = segments;
  19032. this.diameter = diameter;
  19033. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19034. }
  19035. Sphere.prototype._regenerateVertexData = function () {
  19036. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19037. };
  19038. Sphere.prototype.copy = function (id) {
  19039. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19040. };
  19041. return Sphere;
  19042. })(_Primitive);
  19043. Primitives.Sphere = Sphere;
  19044. var Cylinder = (function (_super) {
  19045. __extends(Cylinder, _super);
  19046. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19047. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19048. this.height = height;
  19049. this.diameterTop = diameterTop;
  19050. this.diameterBottom = diameterBottom;
  19051. this.tessellation = tessellation;
  19052. this.subdivisions = subdivisions;
  19053. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19054. }
  19055. Cylinder.prototype._regenerateVertexData = function () {
  19056. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19057. };
  19058. Cylinder.prototype.copy = function (id) {
  19059. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19060. };
  19061. return Cylinder;
  19062. })(_Primitive);
  19063. Primitives.Cylinder = Cylinder;
  19064. var Torus = (function (_super) {
  19065. __extends(Torus, _super);
  19066. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19067. this.diameter = diameter;
  19068. this.thickness = thickness;
  19069. this.tessellation = tessellation;
  19070. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19071. }
  19072. Torus.prototype._regenerateVertexData = function () {
  19073. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19074. };
  19075. Torus.prototype.copy = function (id) {
  19076. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19077. };
  19078. return Torus;
  19079. })(_Primitive);
  19080. Primitives.Torus = Torus;
  19081. var Ground = (function (_super) {
  19082. __extends(Ground, _super);
  19083. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19084. this.width = width;
  19085. this.height = height;
  19086. this.subdivisions = subdivisions;
  19087. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19088. }
  19089. Ground.prototype._regenerateVertexData = function () {
  19090. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19091. };
  19092. Ground.prototype.copy = function (id) {
  19093. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19094. };
  19095. return Ground;
  19096. })(_Primitive);
  19097. Primitives.Ground = Ground;
  19098. var TiledGround = (function (_super) {
  19099. __extends(TiledGround, _super);
  19100. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19101. this.xmin = xmin;
  19102. this.zmin = zmin;
  19103. this.xmax = xmax;
  19104. this.zmax = zmax;
  19105. this.subdivisions = subdivisions;
  19106. this.precision = precision;
  19107. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19108. }
  19109. TiledGround.prototype._regenerateVertexData = function () {
  19110. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19111. };
  19112. TiledGround.prototype.copy = function (id) {
  19113. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19114. };
  19115. return TiledGround;
  19116. })(_Primitive);
  19117. Primitives.TiledGround = TiledGround;
  19118. var Plane = (function (_super) {
  19119. __extends(Plane, _super);
  19120. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19121. this.size = size;
  19122. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19123. }
  19124. Plane.prototype._regenerateVertexData = function () {
  19125. return BABYLON.VertexData.CreatePlane(this.size);
  19126. };
  19127. Plane.prototype.copy = function (id) {
  19128. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19129. };
  19130. return Plane;
  19131. })(_Primitive);
  19132. Primitives.Plane = Plane;
  19133. var TorusKnot = (function (_super) {
  19134. __extends(TorusKnot, _super);
  19135. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19136. this.radius = radius;
  19137. this.tube = tube;
  19138. this.radialSegments = radialSegments;
  19139. this.tubularSegments = tubularSegments;
  19140. this.p = p;
  19141. this.q = q;
  19142. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19143. }
  19144. TorusKnot.prototype._regenerateVertexData = function () {
  19145. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19146. };
  19147. TorusKnot.prototype.copy = function (id) {
  19148. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19149. };
  19150. return TorusKnot;
  19151. })(_Primitive);
  19152. Primitives.TorusKnot = TorusKnot;
  19153. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19154. var Primitives = Geometry.Primitives;
  19155. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19156. var Geometry = BABYLON.Geometry;
  19157. })(BABYLON || (BABYLON = {}));
  19158. var __extends = this.__extends || function (d, b) {
  19159. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19160. function __() { this.constructor = d; }
  19161. __.prototype = b.prototype;
  19162. d.prototype = new __();
  19163. };
  19164. var BABYLON;
  19165. (function (BABYLON) {
  19166. var Gamepads = (function () {
  19167. function Gamepads(ongamedpadconnected) {
  19168. var _this = this;
  19169. this.babylonGamepads = [];
  19170. this.oneGamepadConnected = false;
  19171. this.isMonitoring = false;
  19172. this.gamepadEventSupported = 'GamepadEvent' in window;
  19173. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19174. 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=";
  19175. this._callbackGamepadConnected = ongamedpadconnected;
  19176. if (this.gamepadSupportAvailable) {
  19177. if (this.gamepadEventSupported) {
  19178. window.addEventListener('gamepadconnected', function (evt) {
  19179. _this._onGamepadConnected(evt);
  19180. }, false);
  19181. window.addEventListener('gamepaddisconnected', function (evt) {
  19182. _this._onGamepadDisconnected(evt);
  19183. }, false);
  19184. } else {
  19185. this._startMonitoringGamepads();
  19186. }
  19187. if (!this.oneGamepadConnected) {
  19188. this._insertGamepadDOMInstructions();
  19189. }
  19190. } else {
  19191. this._insertGamepadDOMNotSupported();
  19192. }
  19193. }
  19194. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19195. Gamepads.gamepadDOMInfo = document.createElement("div");
  19196. var buttonAImage = document.createElement("img");
  19197. buttonAImage.src = this.buttonADataURL;
  19198. var spanMessage = document.createElement("span");
  19199. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19200. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19201. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19202. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19203. Gamepads.gamepadDOMInfo.style.width = "100%";
  19204. Gamepads.gamepadDOMInfo.style.height = "48px";
  19205. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19206. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19207. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19208. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19209. buttonAImage.style.position = "relative";
  19210. buttonAImage.style.bottom = "8px";
  19211. spanMessage.style.position = "relative";
  19212. spanMessage.style.fontSize = "32px";
  19213. spanMessage.style.bottom = "32px";
  19214. spanMessage.style.color = "green";
  19215. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19216. };
  19217. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19218. Gamepads.gamepadDOMInfo = document.createElement("div");
  19219. var spanMessage = document.createElement("span");
  19220. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19221. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19222. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19223. Gamepads.gamepadDOMInfo.style.width = "100%";
  19224. Gamepads.gamepadDOMInfo.style.height = "40px";
  19225. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19226. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19227. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19228. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19229. spanMessage.style.position = "relative";
  19230. spanMessage.style.fontSize = "32px";
  19231. spanMessage.style.color = "red";
  19232. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19233. };
  19234. Gamepads.prototype.dispose = function () {
  19235. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19236. };
  19237. Gamepads.prototype._onGamepadConnected = function (evt) {
  19238. var newGamepad = this._addNewGamepad(evt.gamepad);
  19239. if (this._callbackGamepadConnected)
  19240. this._callbackGamepadConnected(newGamepad);
  19241. this._startMonitoringGamepads();
  19242. };
  19243. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19244. if (!this.oneGamepadConnected) {
  19245. this.oneGamepadConnected = true;
  19246. if (Gamepads.gamepadDOMInfo) {
  19247. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19248. Gamepads.gamepadDOMInfo = null;
  19249. }
  19250. }
  19251. var newGamepad;
  19252. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19253. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19254. } else {
  19255. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19256. }
  19257. this.babylonGamepads.push(newGamepad);
  19258. return newGamepad;
  19259. };
  19260. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19261. for (var i in this.babylonGamepads) {
  19262. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19263. this.babylonGamepads.splice(i, 1);
  19264. break;
  19265. }
  19266. }
  19267. if (this.babylonGamepads.length == 0) {
  19268. this._stopMonitoringGamepads();
  19269. }
  19270. };
  19271. Gamepads.prototype._startMonitoringGamepads = function () {
  19272. if (!this.isMonitoring) {
  19273. this.isMonitoring = true;
  19274. this._checkGamepadsStatus();
  19275. }
  19276. };
  19277. Gamepads.prototype._stopMonitoringGamepads = function () {
  19278. this.isMonitoring = false;
  19279. };
  19280. Gamepads.prototype._checkGamepadsStatus = function () {
  19281. var _this = this;
  19282. this._updateGamepadObjects();
  19283. for (var i in this.babylonGamepads) {
  19284. this.babylonGamepads[i].update();
  19285. }
  19286. if (this.isMonitoring) {
  19287. if (window.requestAnimationFrame) {
  19288. window.requestAnimationFrame(function () {
  19289. _this._checkGamepadsStatus();
  19290. });
  19291. } else if (window.mozRequestAnimationFrame) {
  19292. window.mozRequestAnimationFrame(function () {
  19293. _this._checkGamepadsStatus();
  19294. });
  19295. } else if (window.webkitRequestAnimationFrame) {
  19296. window.webkitRequestAnimationFrame(function () {
  19297. _this._checkGamepadsStatus();
  19298. });
  19299. }
  19300. }
  19301. };
  19302. Gamepads.prototype._updateGamepadObjects = function () {
  19303. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19304. for (var i = 0; i < gamepads.length; i++) {
  19305. if (gamepads[i]) {
  19306. if (!(gamepads[i].index in this.babylonGamepads)) {
  19307. var newGamepad = this._addNewGamepad(gamepads[i]);
  19308. if (this._callbackGamepadConnected) {
  19309. this._callbackGamepadConnected(newGamepad);
  19310. }
  19311. } else {
  19312. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19313. }
  19314. }
  19315. }
  19316. };
  19317. return Gamepads;
  19318. })();
  19319. BABYLON.Gamepads = Gamepads;
  19320. var StickValues = (function () {
  19321. function StickValues(x, y) {
  19322. this.x = x;
  19323. this.y = y;
  19324. }
  19325. return StickValues;
  19326. })();
  19327. BABYLON.StickValues = StickValues;
  19328. var Gamepad = (function () {
  19329. function Gamepad(id, index, browserGamepad) {
  19330. this.id = id;
  19331. this.index = index;
  19332. this.browserGamepad = browserGamepad;
  19333. if (this.browserGamepad.axes.length >= 2) {
  19334. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19335. }
  19336. if (this.browserGamepad.axes.length >= 4) {
  19337. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19338. }
  19339. }
  19340. Gamepad.prototype.onleftstickchanged = function (callback) {
  19341. this._onleftstickchanged = callback;
  19342. };
  19343. Gamepad.prototype.onrightstickchanged = function (callback) {
  19344. this._onrightstickchanged = callback;
  19345. };
  19346. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19347. get: function () {
  19348. return this._leftStick;
  19349. },
  19350. set: function (newValues) {
  19351. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19352. this._onleftstickchanged(newValues);
  19353. }
  19354. this._leftStick = newValues;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19360. get: function () {
  19361. return this._rightStick;
  19362. },
  19363. set: function (newValues) {
  19364. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19365. this._onrightstickchanged(newValues);
  19366. }
  19367. this._rightStick = newValues;
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. Gamepad.prototype.update = function () {
  19373. if (this._leftStick) {
  19374. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19375. }
  19376. if (this._rightStick) {
  19377. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19378. }
  19379. };
  19380. return Gamepad;
  19381. })();
  19382. BABYLON.Gamepad = Gamepad;
  19383. var GenericPad = (function (_super) {
  19384. __extends(GenericPad, _super);
  19385. function GenericPad(id, index, gamepad) {
  19386. _super.call(this, id, index, gamepad);
  19387. this.id = id;
  19388. this.index = index;
  19389. this.gamepad = gamepad;
  19390. this._buttons = new Array(gamepad.buttons.length);
  19391. }
  19392. GenericPad.prototype.onbuttondown = function (callback) {
  19393. this._onbuttondown = callback;
  19394. };
  19395. GenericPad.prototype.onbuttonup = function (callback) {
  19396. this._onbuttonup = callback;
  19397. };
  19398. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19399. if (newValue !== currentValue) {
  19400. if (this._onbuttondown && newValue === 1) {
  19401. this._onbuttondown(buttonIndex);
  19402. }
  19403. if (this._onbuttonup && newValue === 0) {
  19404. this._onbuttonup(buttonIndex);
  19405. }
  19406. }
  19407. return newValue;
  19408. };
  19409. GenericPad.prototype.update = function () {
  19410. _super.prototype.update.call(this);
  19411. for (var index = 0; index < this._buttons.length; index++) {
  19412. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19413. }
  19414. };
  19415. return GenericPad;
  19416. })(Gamepad);
  19417. BABYLON.GenericPad = GenericPad;
  19418. (function (Xbox360Button) {
  19419. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19420. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19421. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19422. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19423. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19424. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19425. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19426. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19427. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19428. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19429. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19430. var Xbox360Button = BABYLON.Xbox360Button;
  19431. (function (Xbox360Dpad) {
  19432. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19433. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19434. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19435. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19436. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19437. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19438. var Xbox360Pad = (function (_super) {
  19439. __extends(Xbox360Pad, _super);
  19440. function Xbox360Pad() {
  19441. _super.apply(this, arguments);
  19442. this._leftTrigger = 0;
  19443. this._rightTrigger = 0;
  19444. this._buttonA = 0;
  19445. this._buttonB = 0;
  19446. this._buttonX = 0;
  19447. this._buttonY = 0;
  19448. this._buttonBack = 0;
  19449. this._buttonStart = 0;
  19450. this._buttonLB = 0;
  19451. this._buttonRB = 0;
  19452. this._buttonLeftStick = 0;
  19453. this._buttonRightStick = 0;
  19454. this._dPadUp = 0;
  19455. this._dPadDown = 0;
  19456. this._dPadLeft = 0;
  19457. this._dPadRight = 0;
  19458. }
  19459. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19460. this._onlefttriggerchanged = callback;
  19461. };
  19462. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19463. this._onrighttriggerchanged = callback;
  19464. };
  19465. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19466. get: function () {
  19467. return this._leftTrigger;
  19468. },
  19469. set: function (newValue) {
  19470. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19471. this._onlefttriggerchanged(newValue);
  19472. }
  19473. this._leftTrigger = newValue;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19479. get: function () {
  19480. return this._rightTrigger;
  19481. },
  19482. set: function (newValue) {
  19483. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19484. this._onrighttriggerchanged(newValue);
  19485. }
  19486. this._rightTrigger = newValue;
  19487. },
  19488. enumerable: true,
  19489. configurable: true
  19490. });
  19491. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19492. this._onbuttondown = callback;
  19493. };
  19494. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19495. this._onbuttonup = callback;
  19496. };
  19497. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19498. this._ondpaddown = callback;
  19499. };
  19500. Xbox360Pad.prototype.ondpadup = function (callback) {
  19501. this._ondpadup = callback;
  19502. };
  19503. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19504. if (newValue !== currentValue) {
  19505. if (this._onbuttondown && newValue === 1) {
  19506. this._onbuttondown(buttonType);
  19507. }
  19508. if (this._onbuttonup && newValue === 0) {
  19509. this._onbuttonup(buttonType);
  19510. }
  19511. }
  19512. return newValue;
  19513. };
  19514. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19515. if (newValue !== currentValue) {
  19516. if (this._ondpaddown && newValue === 1) {
  19517. this._ondpaddown(buttonType);
  19518. }
  19519. if (this._ondpadup && newValue === 0) {
  19520. this._ondpadup(buttonType);
  19521. }
  19522. }
  19523. return newValue;
  19524. };
  19525. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19526. get: function () {
  19527. return this._buttonA;
  19528. },
  19529. set: function (value) {
  19530. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19536. get: function () {
  19537. return this._buttonB;
  19538. },
  19539. set: function (value) {
  19540. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19546. get: function () {
  19547. return this._buttonX;
  19548. },
  19549. set: function (value) {
  19550. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19556. get: function () {
  19557. return this._buttonY;
  19558. },
  19559. set: function (value) {
  19560. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19566. get: function () {
  19567. return this._buttonStart;
  19568. },
  19569. set: function (value) {
  19570. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19576. get: function () {
  19577. return this._buttonBack;
  19578. },
  19579. set: function (value) {
  19580. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19586. get: function () {
  19587. return this._buttonLB;
  19588. },
  19589. set: function (value) {
  19590. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19596. get: function () {
  19597. return this._buttonRB;
  19598. },
  19599. set: function (value) {
  19600. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19606. get: function () {
  19607. return this._buttonLeftStick;
  19608. },
  19609. set: function (value) {
  19610. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19611. },
  19612. enumerable: true,
  19613. configurable: true
  19614. });
  19615. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19616. get: function () {
  19617. return this._buttonRightStick;
  19618. },
  19619. set: function (value) {
  19620. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19621. },
  19622. enumerable: true,
  19623. configurable: true
  19624. });
  19625. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19626. get: function () {
  19627. return this._dPadUp;
  19628. },
  19629. set: function (value) {
  19630. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19636. get: function () {
  19637. return this._dPadDown;
  19638. },
  19639. set: function (value) {
  19640. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19641. },
  19642. enumerable: true,
  19643. configurable: true
  19644. });
  19645. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19646. get: function () {
  19647. return this._dPadLeft;
  19648. },
  19649. set: function (value) {
  19650. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19651. },
  19652. enumerable: true,
  19653. configurable: true
  19654. });
  19655. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19656. get: function () {
  19657. return this._dPadRight;
  19658. },
  19659. set: function (value) {
  19660. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Xbox360Pad.prototype.update = function () {
  19666. _super.prototype.update.call(this);
  19667. this.buttonA = this.browserGamepad.buttons[0].value;
  19668. this.buttonB = this.browserGamepad.buttons[1].value;
  19669. this.buttonX = this.browserGamepad.buttons[2].value;
  19670. this.buttonY = this.browserGamepad.buttons[3].value;
  19671. this.buttonLB = this.browserGamepad.buttons[4].value;
  19672. this.buttonRB = this.browserGamepad.buttons[5].value;
  19673. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19674. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19675. this.buttonBack = this.browserGamepad.buttons[8].value;
  19676. this.buttonStart = this.browserGamepad.buttons[9].value;
  19677. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19678. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19679. this.dPadUp = this.browserGamepad.buttons[12].value;
  19680. this.dPadDown = this.browserGamepad.buttons[13].value;
  19681. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19682. this.dPadRight = this.browserGamepad.buttons[15].value;
  19683. };
  19684. return Xbox360Pad;
  19685. })(Gamepad);
  19686. BABYLON.Xbox360Pad = Xbox360Pad;
  19687. })(BABYLON || (BABYLON = {}));
  19688. var __extends = this.__extends || function (d, b) {
  19689. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19690. function __() { this.constructor = d; }
  19691. __.prototype = b.prototype;
  19692. d.prototype = new __();
  19693. };
  19694. var BABYLON;
  19695. (function (BABYLON) {
  19696. var GamepadCamera = (function (_super) {
  19697. __extends(GamepadCamera, _super);
  19698. function GamepadCamera(name, position, scene) {
  19699. var _this = this;
  19700. _super.call(this, name, position, scene);
  19701. this.angularSensibility = 200;
  19702. this.moveSensibility = 75;
  19703. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19704. _this._onNewGameConnected(gamepad);
  19705. });
  19706. }
  19707. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19708. if (gamepad.index === 0) {
  19709. this._gamepad = gamepad;
  19710. }
  19711. };
  19712. GamepadCamera.prototype._checkInputs = function () {
  19713. if (!this._gamepad) {
  19714. return;
  19715. }
  19716. var LSValues = this._gamepad.leftStick;
  19717. var normalizedLX = LSValues.x / this.moveSensibility;
  19718. var normalizedLY = LSValues.y / this.moveSensibility;
  19719. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19720. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19721. var RSValues = this._gamepad.rightStick;
  19722. var normalizedRX = RSValues.x / this.angularSensibility;
  19723. var normalizedRY = RSValues.y / this.angularSensibility;
  19724. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19725. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19726. ;
  19727. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19728. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19729. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19730. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19731. };
  19732. GamepadCamera.prototype.dispose = function () {
  19733. this._gamepads.dispose();
  19734. _super.prototype.dispose.call(this);
  19735. };
  19736. return GamepadCamera;
  19737. })(BABYLON.FreeCamera);
  19738. BABYLON.GamepadCamera = GamepadCamera;
  19739. })(BABYLON || (BABYLON = {}));
  19740. var __extends = this.__extends || function (d, b) {
  19741. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19742. function __() { this.constructor = d; }
  19743. __.prototype = b.prototype;
  19744. d.prototype = new __();
  19745. };
  19746. var BABYLON;
  19747. (function (BABYLON) {
  19748. var LinesMesh = (function (_super) {
  19749. __extends(LinesMesh, _super);
  19750. function LinesMesh(name, scene, updatable) {
  19751. if (typeof updatable === "undefined") { updatable = false; }
  19752. _super.call(this, name, scene);
  19753. this.color = new BABYLON.Color3(1, 1, 1);
  19754. this.alpha = 1;
  19755. this._indices = new Array();
  19756. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19757. attributes: ["position"],
  19758. uniforms: ["worldViewProjection", "color"],
  19759. needAlphaBlending: true
  19760. });
  19761. }
  19762. Object.defineProperty(LinesMesh.prototype, "material", {
  19763. get: function () {
  19764. return this._colorShader;
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19770. get: function () {
  19771. return false;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19777. get: function () {
  19778. return false;
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19784. var engine = this.getScene().getEngine();
  19785. var indexToBind = this._geometry.getIndexBuffer();
  19786. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19787. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19788. };
  19789. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19790. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19791. return;
  19792. }
  19793. var engine = this.getScene().getEngine();
  19794. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19795. };
  19796. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19797. return null;
  19798. };
  19799. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19800. this._colorShader.dispose();
  19801. _super.prototype.dispose.call(this, doNotRecurse);
  19802. };
  19803. return LinesMesh;
  19804. })(BABYLON.Mesh);
  19805. BABYLON.LinesMesh = LinesMesh;
  19806. })(BABYLON || (BABYLON = {}));
  19807. var BABYLON;
  19808. (function (BABYLON) {
  19809. var OutlineRenderer = (function () {
  19810. function OutlineRenderer(scene) {
  19811. this._scene = scene;
  19812. }
  19813. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19814. var scene = this._scene;
  19815. var engine = this._scene.getEngine();
  19816. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19817. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19818. return;
  19819. }
  19820. var mesh = subMesh.getRenderingMesh();
  19821. var material = subMesh.getMaterial();
  19822. engine.enableEffect(this._effect);
  19823. this._effect.setFloat("offset", mesh.outlineWidth);
  19824. this._effect.setColor3("color", mesh.outlineColor);
  19825. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19826. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19827. if (useBones) {
  19828. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19829. }
  19830. mesh._bind(subMesh, this._effect, false);
  19831. if (material && material.needAlphaTesting()) {
  19832. var alphaTexture = material.getAlphaTestTexture();
  19833. this._effect.setTexture("diffuseSampler", alphaTexture);
  19834. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19835. }
  19836. if (hardwareInstancedRendering) {
  19837. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19838. } else {
  19839. if (batch.renderSelf[subMesh._id]) {
  19840. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19841. mesh._draw(subMesh, true);
  19842. }
  19843. if (batch.visibleInstances[subMesh._id]) {
  19844. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19845. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19846. this._effect.setMatrix("world", instance.getWorldMatrix());
  19847. mesh._draw(subMesh, true);
  19848. }
  19849. }
  19850. }
  19851. };
  19852. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19853. var defines = [];
  19854. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19855. var mesh = subMesh.getMesh();
  19856. var material = subMesh.getMaterial();
  19857. if (material && material.needAlphaTesting()) {
  19858. defines.push("#define ALPHATEST");
  19859. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19860. attribs.push(BABYLON.VertexBuffer.UVKind);
  19861. defines.push("#define UV1");
  19862. }
  19863. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19864. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19865. defines.push("#define UV2");
  19866. }
  19867. }
  19868. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19871. defines.push("#define BONES");
  19872. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19873. }
  19874. if (useInstances) {
  19875. defines.push("#define INSTANCES");
  19876. attribs.push("world0");
  19877. attribs.push("world1");
  19878. attribs.push("world2");
  19879. attribs.push("world3");
  19880. }
  19881. var join = defines.join("\n");
  19882. if (this._cachedDefines != join) {
  19883. this._cachedDefines = join;
  19884. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19885. }
  19886. return this._effect.isReady();
  19887. };
  19888. return OutlineRenderer;
  19889. })();
  19890. BABYLON.OutlineRenderer = OutlineRenderer;
  19891. })(BABYLON || (BABYLON = {}));
  19892. var BABYLON;
  19893. (function (BABYLON) {
  19894. var MeshAssetTask = (function () {
  19895. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19896. this.name = name;
  19897. this.meshesNames = meshesNames;
  19898. this.rootUrl = rootUrl;
  19899. this.sceneFilename = sceneFilename;
  19900. this.isCompleted = false;
  19901. }
  19902. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19903. var _this = this;
  19904. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19905. _this.loadedMeshes = meshes;
  19906. _this.loadedParticleSystems = particleSystems;
  19907. _this.loadedSkeletons = skeletons;
  19908. _this.isCompleted = true;
  19909. if (_this.onSuccess) {
  19910. _this.onSuccess(_this);
  19911. }
  19912. onSuccess();
  19913. }, null, function () {
  19914. if (_this.onError) {
  19915. _this.onError(_this);
  19916. }
  19917. onError();
  19918. });
  19919. };
  19920. return MeshAssetTask;
  19921. })();
  19922. BABYLON.MeshAssetTask = MeshAssetTask;
  19923. var TextFileAssetTask = (function () {
  19924. function TextFileAssetTask(name, url) {
  19925. this.name = name;
  19926. this.url = url;
  19927. this.isCompleted = false;
  19928. }
  19929. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19930. var _this = this;
  19931. BABYLON.Tools.LoadFile(this.url, function (data) {
  19932. _this.text = data;
  19933. _this.isCompleted = true;
  19934. if (_this.onSuccess) {
  19935. _this.onSuccess(_this);
  19936. }
  19937. onSuccess();
  19938. }, null, scene.database, false, function () {
  19939. if (_this.onError) {
  19940. _this.onError(_this);
  19941. }
  19942. onError();
  19943. });
  19944. };
  19945. return TextFileAssetTask;
  19946. })();
  19947. BABYLON.TextFileAssetTask = TextFileAssetTask;
  19948. var BinaryFileAssetTask = (function () {
  19949. function BinaryFileAssetTask(name, url) {
  19950. this.name = name;
  19951. this.url = url;
  19952. this.isCompleted = false;
  19953. }
  19954. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19955. var _this = this;
  19956. BABYLON.Tools.LoadFile(this.url, function (data) {
  19957. _this.data = data;
  19958. _this.isCompleted = true;
  19959. if (_this.onSuccess) {
  19960. _this.onSuccess(_this);
  19961. }
  19962. onSuccess();
  19963. }, null, scene.database, true, function () {
  19964. if (_this.onError) {
  19965. _this.onError(_this);
  19966. }
  19967. onError();
  19968. });
  19969. };
  19970. return BinaryFileAssetTask;
  19971. })();
  19972. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  19973. var ImageAssetTask = (function () {
  19974. function ImageAssetTask(name, url) {
  19975. this.name = name;
  19976. this.url = url;
  19977. this.isCompleted = false;
  19978. }
  19979. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19980. var _this = this;
  19981. var img = new Image();
  19982. img.onload = function () {
  19983. _this.image = img;
  19984. _this.isCompleted = true;
  19985. if (_this.onSuccess) {
  19986. _this.onSuccess(_this);
  19987. }
  19988. onSuccess();
  19989. };
  19990. img.onerror = function () {
  19991. if (_this.onError) {
  19992. _this.onError(_this);
  19993. }
  19994. onError();
  19995. };
  19996. img.src = this.url;
  19997. };
  19998. return ImageAssetTask;
  19999. })();
  20000. BABYLON.ImageAssetTask = ImageAssetTask;
  20001. var AssetsManager = (function () {
  20002. function AssetsManager(scene) {
  20003. this._tasks = new Array();
  20004. this._waitingTasksCount = 0;
  20005. this.useDefaultLoadingScreen = true;
  20006. this._scene = scene;
  20007. }
  20008. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20009. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20010. this._tasks.push(task);
  20011. return task;
  20012. };
  20013. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20014. var task = new TextFileAssetTask(taskName, url);
  20015. this._tasks.push(task);
  20016. return task;
  20017. };
  20018. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20019. var task = new BinaryFileAssetTask(taskName, url);
  20020. this._tasks.push(task);
  20021. return task;
  20022. };
  20023. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20024. var task = new ImageAssetTask(taskName, url);
  20025. this._tasks.push(task);
  20026. return task;
  20027. };
  20028. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20029. this._waitingTasksCount--;
  20030. if (this._waitingTasksCount === 0) {
  20031. if (this.onFinish) {
  20032. this.onFinish(this._tasks);
  20033. }
  20034. this._scene.getEngine().hideLoadingUI();
  20035. }
  20036. };
  20037. AssetsManager.prototype._runTask = function (task) {
  20038. var _this = this;
  20039. task.run(this._scene, function () {
  20040. if (_this.onTaskSuccess) {
  20041. _this.onTaskSuccess(task);
  20042. }
  20043. _this._decreaseWaitingTasksCount();
  20044. }, function () {
  20045. if (_this.onTaskError) {
  20046. _this.onTaskError(task);
  20047. }
  20048. _this._decreaseWaitingTasksCount();
  20049. });
  20050. };
  20051. AssetsManager.prototype.reset = function () {
  20052. this._tasks = new Array();
  20053. return this;
  20054. };
  20055. AssetsManager.prototype.load = function () {
  20056. this._waitingTasksCount = this._tasks.length;
  20057. if (this._waitingTasksCount === 0) {
  20058. if (this.onFinish) {
  20059. this.onFinish(this._tasks);
  20060. }
  20061. return this;
  20062. }
  20063. if (this.useDefaultLoadingScreen) {
  20064. this._scene.getEngine().displayLoadingUI();
  20065. }
  20066. for (var index = 0; index < this._tasks.length; index++) {
  20067. var task = this._tasks[index];
  20068. this._runTask(task);
  20069. }
  20070. return this;
  20071. };
  20072. return AssetsManager;
  20073. })();
  20074. BABYLON.AssetsManager = AssetsManager;
  20075. })(BABYLON || (BABYLON = {}));