babylon.1.14-beta-debug.js 1006 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382
  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.add = function (other) {
  719. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  720. };
  721. Quaternion.prototype.subtract = function (other) {
  722. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  723. };
  724. Quaternion.prototype.scale = function (value) {
  725. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  726. };
  727. Quaternion.prototype.multiply = function (q1) {
  728. var result = new Quaternion(0, 0, 0, 1.0);
  729. this.multiplyToRef(q1, result);
  730. return result;
  731. };
  732. Quaternion.prototype.multiplyToRef = function (q1, result) {
  733. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  734. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  735. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  736. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  737. };
  738. Quaternion.prototype.length = function () {
  739. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  740. };
  741. Quaternion.prototype.normalize = function () {
  742. var length = 1.0 / this.length();
  743. this.x *= length;
  744. this.y *= length;
  745. this.z *= length;
  746. this.w *= length;
  747. };
  748. Quaternion.prototype.toEulerAngles = function () {
  749. var qx = this.x;
  750. var qy = this.y;
  751. var qz = this.z;
  752. var qw = this.w;
  753. var sqx = qx * qx;
  754. var sqy = qy * qy;
  755. var sqz = qz * qz;
  756. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  757. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  758. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  759. var gimbaLockTest = qx * qy + qz * qw;
  760. if (gimbaLockTest > 0.499) {
  761. yaw = 2.0 * Math.atan2(qx, qw);
  762. roll = 0;
  763. } else if (gimbaLockTest < -0.499) {
  764. yaw = -2.0 * Math.atan2(qx, qw);
  765. roll = 0;
  766. }
  767. return new Vector3(pitch, yaw, roll);
  768. };
  769. Quaternion.prototype.toRotationMatrix = function (result) {
  770. var xx = this.x * this.x;
  771. var yy = this.y * this.y;
  772. var zz = this.z * this.z;
  773. var xy = this.x * this.y;
  774. var zw = this.z * this.w;
  775. var zx = this.z * this.x;
  776. var yw = this.y * this.w;
  777. var yz = this.y * this.z;
  778. var xw = this.x * this.w;
  779. result.m[0] = 1.0 - (2.0 * (yy + zz));
  780. result.m[1] = 2.0 * (xy + zw);
  781. result.m[2] = 2.0 * (zx - yw);
  782. result.m[3] = 0;
  783. result.m[4] = 2.0 * (xy - zw);
  784. result.m[5] = 1.0 - (2.0 * (zz + xx));
  785. result.m[6] = 2.0 * (yz + xw);
  786. result.m[7] = 0;
  787. result.m[8] = 2.0 * (zx + yw);
  788. result.m[9] = 2.0 * (yz - xw);
  789. result.m[10] = 1.0 - (2.0 * (yy + xx));
  790. result.m[11] = 0;
  791. result.m[12] = 0;
  792. result.m[13] = 0;
  793. result.m[14] = 0;
  794. result.m[15] = 1.0;
  795. };
  796. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  797. var data = matrix.m;
  798. var m11 = data[0], m12 = data[4], m13 = data[8];
  799. var m21 = data[1], m22 = data[5], m23 = data[9];
  800. var m31 = data[2], m32 = data[6], m33 = data[10];
  801. var trace = m11 + m22 + m33;
  802. var s;
  803. if (trace > 0) {
  804. s = 0.5 / Math.sqrt(trace + 1.0);
  805. this.w = 0.25 / s;
  806. this.x = (m32 - m23) * s;
  807. this.y = (m13 - m31) * s;
  808. this.z = (m21 - m12) * s;
  809. return;
  810. }
  811. if (m11 > m22 && m11 > m33) {
  812. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  813. this.w = (m32 - m23) / s;
  814. this.x = 0.25 * s;
  815. this.y = (m12 + m21) / s;
  816. this.z = (m13 + m31) / s;
  817. return;
  818. }
  819. if (m22 > m33) {
  820. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  821. this.w = (m13 - m31) / s;
  822. this.x = (m12 + m21) / s;
  823. this.y = 0.25 * s;
  824. this.z = (m23 + m32) / s;
  825. return;
  826. }
  827. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  828. this.w = (m21 - m12) / s;
  829. this.x = (m13 + m31) / s;
  830. this.y = (m23 + m32) / s;
  831. this.z = 0.25 * s;
  832. };
  833. Quaternion.RotationAxis = function (axis, angle) {
  834. var result = new Quaternion();
  835. var sin = Math.sin(angle / 2);
  836. result.w = Math.cos(angle / 2);
  837. result.x = axis.x * sin;
  838. result.y = axis.y * sin;
  839. result.z = axis.z * sin;
  840. return result;
  841. };
  842. Quaternion.FromArray = function (array, offset) {
  843. if (!offset) {
  844. offset = 0;
  845. }
  846. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  847. };
  848. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  849. var result = new Quaternion();
  850. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  851. return result;
  852. };
  853. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  854. var halfRoll = roll * 0.5;
  855. var halfPitch = pitch * 0.5;
  856. var halfYaw = yaw * 0.5;
  857. var sinRoll = Math.sin(halfRoll);
  858. var cosRoll = Math.cos(halfRoll);
  859. var sinPitch = Math.sin(halfPitch);
  860. var cosPitch = Math.cos(halfPitch);
  861. var sinYaw = Math.sin(halfYaw);
  862. var cosYaw = Math.cos(halfYaw);
  863. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  864. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  865. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  866. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  867. };
  868. Quaternion.Slerp = function (left, right, amount) {
  869. var num2;
  870. var num3;
  871. var num = amount;
  872. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  873. var flag = false;
  874. if (num4 < 0) {
  875. flag = true;
  876. num4 = -num4;
  877. }
  878. if (num4 > 0.999999) {
  879. num3 = 1 - num;
  880. num2 = flag ? -num : num;
  881. } else {
  882. var num5 = Math.acos(num4);
  883. var num6 = (1.0 / Math.sin(num5));
  884. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  885. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  886. }
  887. 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));
  888. };
  889. return Quaternion;
  890. })();
  891. BABYLON.Quaternion = Quaternion;
  892. var Matrix = (function () {
  893. function Matrix() {
  894. this.m = new Float32Array(16);
  895. }
  896. Matrix.prototype.isIdentity = function () {
  897. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  898. return false;
  899. 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)
  900. return false;
  901. return true;
  902. };
  903. Matrix.prototype.determinant = function () {
  904. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  905. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  906. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  907. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  908. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  909. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  910. 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))));
  911. };
  912. Matrix.prototype.toArray = function () {
  913. return this.m;
  914. };
  915. Matrix.prototype.asArray = function () {
  916. return this.toArray();
  917. };
  918. Matrix.prototype.invert = function () {
  919. this.invertToRef(this);
  920. };
  921. Matrix.prototype.invertToRef = function (other) {
  922. var l1 = this.m[0];
  923. var l2 = this.m[1];
  924. var l3 = this.m[2];
  925. var l4 = this.m[3];
  926. var l5 = this.m[4];
  927. var l6 = this.m[5];
  928. var l7 = this.m[6];
  929. var l8 = this.m[7];
  930. var l9 = this.m[8];
  931. var l10 = this.m[9];
  932. var l11 = this.m[10];
  933. var l12 = this.m[11];
  934. var l13 = this.m[12];
  935. var l14 = this.m[13];
  936. var l15 = this.m[14];
  937. var l16 = this.m[15];
  938. var l17 = (l11 * l16) - (l12 * l15);
  939. var l18 = (l10 * l16) - (l12 * l14);
  940. var l19 = (l10 * l15) - (l11 * l14);
  941. var l20 = (l9 * l16) - (l12 * l13);
  942. var l21 = (l9 * l15) - (l11 * l13);
  943. var l22 = (l9 * l14) - (l10 * l13);
  944. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  945. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  946. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  947. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  948. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  949. var l28 = (l7 * l16) - (l8 * l15);
  950. var l29 = (l6 * l16) - (l8 * l14);
  951. var l30 = (l6 * l15) - (l7 * l14);
  952. var l31 = (l5 * l16) - (l8 * l13);
  953. var l32 = (l5 * l15) - (l7 * l13);
  954. var l33 = (l5 * l14) - (l6 * l13);
  955. var l34 = (l7 * l12) - (l8 * l11);
  956. var l35 = (l6 * l12) - (l8 * l10);
  957. var l36 = (l6 * l11) - (l7 * l10);
  958. var l37 = (l5 * l12) - (l8 * l9);
  959. var l38 = (l5 * l11) - (l7 * l9);
  960. var l39 = (l5 * l10) - (l6 * l9);
  961. other.m[0] = l23 * l27;
  962. other.m[4] = l24 * l27;
  963. other.m[8] = l25 * l27;
  964. other.m[12] = l26 * l27;
  965. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  966. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  967. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  968. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  969. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  970. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  971. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  972. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  973. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  974. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  975. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  976. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  977. };
  978. Matrix.prototype.setTranslation = function (vector3) {
  979. this.m[12] = vector3.x;
  980. this.m[13] = vector3.y;
  981. this.m[14] = vector3.z;
  982. };
  983. Matrix.prototype.multiply = function (other) {
  984. var result = new Matrix();
  985. this.multiplyToRef(other, result);
  986. return result;
  987. };
  988. Matrix.prototype.copyFrom = function (other) {
  989. for (var index = 0; index < 16; index++) {
  990. this.m[index] = other.m[index];
  991. }
  992. };
  993. Matrix.prototype.copyToArray = function (array, offset) {
  994. if (typeof offset === "undefined") { offset = 0; }
  995. for (var index = 0; index < 16; index++) {
  996. array[offset + index] = this.m[index];
  997. }
  998. };
  999. Matrix.prototype.multiplyToRef = function (other, result) {
  1000. this.multiplyToArray(other, result.m, 0);
  1001. };
  1002. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1003. var tm0 = this.m[0];
  1004. var tm1 = this.m[1];
  1005. var tm2 = this.m[2];
  1006. var tm3 = this.m[3];
  1007. var tm4 = this.m[4];
  1008. var tm5 = this.m[5];
  1009. var tm6 = this.m[6];
  1010. var tm7 = this.m[7];
  1011. var tm8 = this.m[8];
  1012. var tm9 = this.m[9];
  1013. var tm10 = this.m[10];
  1014. var tm11 = this.m[11];
  1015. var tm12 = this.m[12];
  1016. var tm13 = this.m[13];
  1017. var tm14 = this.m[14];
  1018. var tm15 = this.m[15];
  1019. var om0 = other.m[0];
  1020. var om1 = other.m[1];
  1021. var om2 = other.m[2];
  1022. var om3 = other.m[3];
  1023. var om4 = other.m[4];
  1024. var om5 = other.m[5];
  1025. var om6 = other.m[6];
  1026. var om7 = other.m[7];
  1027. var om8 = other.m[8];
  1028. var om9 = other.m[9];
  1029. var om10 = other.m[10];
  1030. var om11 = other.m[11];
  1031. var om12 = other.m[12];
  1032. var om13 = other.m[13];
  1033. var om14 = other.m[14];
  1034. var om15 = other.m[15];
  1035. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1036. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1037. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1038. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1039. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1040. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1041. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1042. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1043. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1044. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1045. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1046. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1047. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1048. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1049. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1050. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1051. };
  1052. Matrix.prototype.equals = function (value) {
  1053. 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]);
  1054. };
  1055. Matrix.prototype.clone = function () {
  1056. 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]);
  1057. };
  1058. Matrix.FromArray = function (array, offset) {
  1059. var result = new Matrix();
  1060. if (!offset) {
  1061. offset = 0;
  1062. }
  1063. Matrix.FromArrayToRef(array, offset, result);
  1064. return result;
  1065. };
  1066. Matrix.FromArrayToRef = function (array, offset, result) {
  1067. for (var index = 0; index < 16; index++) {
  1068. result.m[index] = array[index + offset];
  1069. }
  1070. };
  1071. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1072. result.m[0] = initialM11;
  1073. result.m[1] = initialM12;
  1074. result.m[2] = initialM13;
  1075. result.m[3] = initialM14;
  1076. result.m[4] = initialM21;
  1077. result.m[5] = initialM22;
  1078. result.m[6] = initialM23;
  1079. result.m[7] = initialM24;
  1080. result.m[8] = initialM31;
  1081. result.m[9] = initialM32;
  1082. result.m[10] = initialM33;
  1083. result.m[11] = initialM34;
  1084. result.m[12] = initialM41;
  1085. result.m[13] = initialM42;
  1086. result.m[14] = initialM43;
  1087. result.m[15] = initialM44;
  1088. };
  1089. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1090. var result = new Matrix();
  1091. result.m[0] = initialM11;
  1092. result.m[1] = initialM12;
  1093. result.m[2] = initialM13;
  1094. result.m[3] = initialM14;
  1095. result.m[4] = initialM21;
  1096. result.m[5] = initialM22;
  1097. result.m[6] = initialM23;
  1098. result.m[7] = initialM24;
  1099. result.m[8] = initialM31;
  1100. result.m[9] = initialM32;
  1101. result.m[10] = initialM33;
  1102. result.m[11] = initialM34;
  1103. result.m[12] = initialM41;
  1104. result.m[13] = initialM42;
  1105. result.m[14] = initialM43;
  1106. result.m[15] = initialM44;
  1107. return result;
  1108. };
  1109. Matrix.Identity = function () {
  1110. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1111. };
  1112. Matrix.IdentityToRef = function (result) {
  1113. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1114. };
  1115. Matrix.Zero = function () {
  1116. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1117. };
  1118. Matrix.RotationX = function (angle) {
  1119. var result = new Matrix();
  1120. Matrix.RotationXToRef(angle, result);
  1121. return result;
  1122. };
  1123. Matrix.RotationXToRef = function (angle, result) {
  1124. var s = Math.sin(angle);
  1125. var c = Math.cos(angle);
  1126. result.m[0] = 1.0;
  1127. result.m[15] = 1.0;
  1128. result.m[5] = c;
  1129. result.m[10] = c;
  1130. result.m[9] = -s;
  1131. result.m[6] = s;
  1132. result.m[1] = 0;
  1133. result.m[2] = 0;
  1134. result.m[3] = 0;
  1135. result.m[4] = 0;
  1136. result.m[7] = 0;
  1137. result.m[8] = 0;
  1138. result.m[11] = 0;
  1139. result.m[12] = 0;
  1140. result.m[13] = 0;
  1141. result.m[14] = 0;
  1142. };
  1143. Matrix.RotationY = function (angle) {
  1144. var result = new Matrix();
  1145. Matrix.RotationYToRef(angle, result);
  1146. return result;
  1147. };
  1148. Matrix.RotationYToRef = function (angle, result) {
  1149. var s = Math.sin(angle);
  1150. var c = Math.cos(angle);
  1151. result.m[5] = 1.0;
  1152. result.m[15] = 1.0;
  1153. result.m[0] = c;
  1154. result.m[2] = -s;
  1155. result.m[8] = s;
  1156. result.m[10] = c;
  1157. result.m[1] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[6] = 0;
  1161. result.m[7] = 0;
  1162. result.m[9] = 0;
  1163. result.m[11] = 0;
  1164. result.m[12] = 0;
  1165. result.m[13] = 0;
  1166. result.m[14] = 0;
  1167. };
  1168. Matrix.RotationZ = function (angle) {
  1169. var result = new Matrix();
  1170. Matrix.RotationZToRef(angle, result);
  1171. return result;
  1172. };
  1173. Matrix.RotationZToRef = function (angle, result) {
  1174. var s = Math.sin(angle);
  1175. var c = Math.cos(angle);
  1176. result.m[10] = 1.0;
  1177. result.m[15] = 1.0;
  1178. result.m[0] = c;
  1179. result.m[1] = s;
  1180. result.m[4] = -s;
  1181. result.m[5] = c;
  1182. result.m[2] = 0;
  1183. result.m[3] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[8] = 0;
  1187. result.m[9] = 0;
  1188. result.m[11] = 0;
  1189. result.m[12] = 0;
  1190. result.m[13] = 0;
  1191. result.m[14] = 0;
  1192. };
  1193. Matrix.RotationAxis = function (axis, angle) {
  1194. var s = Math.sin(-angle);
  1195. var c = Math.cos(-angle);
  1196. var c1 = 1 - c;
  1197. axis.normalize();
  1198. var result = Matrix.Zero();
  1199. result.m[0] = (axis.x * axis.x) * c1 + c;
  1200. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1201. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1202. result.m[3] = 0.0;
  1203. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1204. result.m[5] = (axis.y * axis.y) * c1 + c;
  1205. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1206. result.m[7] = 0.0;
  1207. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1208. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1209. result.m[10] = (axis.z * axis.z) * c1 + c;
  1210. result.m[11] = 0.0;
  1211. result.m[15] = 1.0;
  1212. return result;
  1213. };
  1214. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1215. var result = new Matrix();
  1216. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1217. return result;
  1218. };
  1219. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1220. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1221. this._tempQuaternion.toRotationMatrix(result);
  1222. };
  1223. Matrix.Scaling = function (x, y, z) {
  1224. var result = Matrix.Zero();
  1225. Matrix.ScalingToRef(x, y, z, result);
  1226. return result;
  1227. };
  1228. Matrix.ScalingToRef = function (x, y, z, result) {
  1229. result.m[0] = x;
  1230. result.m[1] = 0;
  1231. result.m[2] = 0;
  1232. result.m[3] = 0;
  1233. result.m[4] = 0;
  1234. result.m[5] = y;
  1235. result.m[6] = 0;
  1236. result.m[7] = 0;
  1237. result.m[8] = 0;
  1238. result.m[9] = 0;
  1239. result.m[10] = z;
  1240. result.m[11] = 0;
  1241. result.m[12] = 0;
  1242. result.m[13] = 0;
  1243. result.m[14] = 0;
  1244. result.m[15] = 1.0;
  1245. };
  1246. Matrix.Translation = function (x, y, z) {
  1247. var result = Matrix.Identity();
  1248. Matrix.TranslationToRef(x, y, z, result);
  1249. return result;
  1250. };
  1251. Matrix.TranslationToRef = function (x, y, z, result) {
  1252. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1253. };
  1254. Matrix.LookAtLH = function (eye, target, up) {
  1255. var result = Matrix.Zero();
  1256. Matrix.LookAtLHToRef(eye, target, up, result);
  1257. return result;
  1258. };
  1259. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1260. target.subtractToRef(eye, this._zAxis);
  1261. this._zAxis.normalize();
  1262. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1263. this._xAxis.normalize();
  1264. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1265. this._yAxis.normalize();
  1266. var ex = -Vector3.Dot(this._xAxis, eye);
  1267. var ey = -Vector3.Dot(this._yAxis, eye);
  1268. var ez = -Vector3.Dot(this._zAxis, eye);
  1269. 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);
  1270. };
  1271. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1272. var hw = 2.0 / width;
  1273. var hh = 2.0 / height;
  1274. var id = 1.0 / (zfar - znear);
  1275. var nid = znear / (znear - zfar);
  1276. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1277. };
  1278. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1279. var matrix = Matrix.Zero();
  1280. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1281. return matrix;
  1282. };
  1283. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1284. result.m[0] = 2.0 / (right - left);
  1285. result.m[1] = result.m[2] = result.m[3] = 0;
  1286. result.m[5] = 2.0 / (top - bottom);
  1287. result.m[4] = result.m[6] = result.m[7] = 0;
  1288. result.m[10] = -1.0 / (znear - zfar);
  1289. result.m[8] = result.m[9] = result.m[11] = 0;
  1290. result.m[12] = (left + right) / (left - right);
  1291. result.m[13] = (top + bottom) / (bottom - top);
  1292. result.m[14] = znear / (znear - zfar);
  1293. result.m[15] = 1.0;
  1294. };
  1295. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1296. var matrix = Matrix.Zero();
  1297. matrix.m[0] = (2.0 * znear) / width;
  1298. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1299. matrix.m[5] = (2.0 * znear) / height;
  1300. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1301. matrix.m[10] = -zfar / (znear - zfar);
  1302. matrix.m[8] = matrix.m[9] = 0.0;
  1303. matrix.m[11] = 1.0;
  1304. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1305. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1306. return matrix;
  1307. };
  1308. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1309. var matrix = Matrix.Zero();
  1310. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1311. return matrix;
  1312. };
  1313. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1314. var tan = 1.0 / (Math.tan(fov * 0.5));
  1315. result.m[0] = tan / aspect;
  1316. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1317. result.m[5] = tan;
  1318. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1319. result.m[8] = result.m[9] = 0.0;
  1320. result.m[10] = -zfar / (znear - zfar);
  1321. result.m[11] = 1.0;
  1322. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1323. result.m[14] = (znear * zfar) / (znear - zfar);
  1324. };
  1325. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1326. var cw = viewport.width;
  1327. var ch = viewport.height;
  1328. var cx = viewport.x;
  1329. var cy = viewport.y;
  1330. 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);
  1331. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1332. };
  1333. Matrix.Transpose = function (matrix) {
  1334. var result = new Matrix();
  1335. result.m[0] = matrix.m[0];
  1336. result.m[1] = matrix.m[4];
  1337. result.m[2] = matrix.m[8];
  1338. result.m[3] = matrix.m[12];
  1339. result.m[4] = matrix.m[1];
  1340. result.m[5] = matrix.m[5];
  1341. result.m[6] = matrix.m[9];
  1342. result.m[7] = matrix.m[13];
  1343. result.m[8] = matrix.m[2];
  1344. result.m[9] = matrix.m[6];
  1345. result.m[10] = matrix.m[10];
  1346. result.m[11] = matrix.m[14];
  1347. result.m[12] = matrix.m[3];
  1348. result.m[13] = matrix.m[7];
  1349. result.m[14] = matrix.m[11];
  1350. result.m[15] = matrix.m[15];
  1351. return result;
  1352. };
  1353. Matrix.Reflection = function (plane) {
  1354. var matrix = new Matrix();
  1355. Matrix.ReflectionToRef(plane, matrix);
  1356. return matrix;
  1357. };
  1358. Matrix.ReflectionToRef = function (plane, result) {
  1359. plane.normalize();
  1360. var x = plane.normal.x;
  1361. var y = plane.normal.y;
  1362. var z = plane.normal.z;
  1363. var temp = -2 * x;
  1364. var temp2 = -2 * y;
  1365. var temp3 = -2 * z;
  1366. result.m[0] = (temp * x) + 1;
  1367. result.m[1] = temp2 * x;
  1368. result.m[2] = temp3 * x;
  1369. result.m[3] = 0.0;
  1370. result.m[4] = temp * y;
  1371. result.m[5] = (temp2 * y) + 1;
  1372. result.m[6] = temp3 * y;
  1373. result.m[7] = 0.0;
  1374. result.m[8] = temp * z;
  1375. result.m[9] = temp2 * z;
  1376. result.m[10] = (temp3 * z) + 1;
  1377. result.m[11] = 0.0;
  1378. result.m[12] = temp * plane.d;
  1379. result.m[13] = temp2 * plane.d;
  1380. result.m[14] = temp3 * plane.d;
  1381. result.m[15] = 1.0;
  1382. };
  1383. Matrix._tempQuaternion = new Quaternion();
  1384. Matrix._xAxis = Vector3.Zero();
  1385. Matrix._yAxis = Vector3.Zero();
  1386. Matrix._zAxis = Vector3.Zero();
  1387. return Matrix;
  1388. })();
  1389. BABYLON.Matrix = Matrix;
  1390. var Plane = (function () {
  1391. function Plane(a, b, c, d) {
  1392. this.normal = new Vector3(a, b, c);
  1393. this.d = d;
  1394. }
  1395. Plane.prototype.asArray = function () {
  1396. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1397. };
  1398. Plane.prototype.clone = function () {
  1399. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1400. };
  1401. Plane.prototype.normalize = function () {
  1402. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1403. var magnitude = 0;
  1404. if (norm != 0) {
  1405. magnitude = 1.0 / norm;
  1406. }
  1407. this.normal.x *= magnitude;
  1408. this.normal.y *= magnitude;
  1409. this.normal.z *= magnitude;
  1410. this.d *= magnitude;
  1411. };
  1412. Plane.prototype.transform = function (transformation) {
  1413. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1414. var x = this.normal.x;
  1415. var y = this.normal.y;
  1416. var z = this.normal.z;
  1417. var d = this.d;
  1418. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1419. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1420. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1421. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1422. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1423. };
  1424. Plane.prototype.dotCoordinate = function (point) {
  1425. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1426. };
  1427. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1428. var x1 = point2.x - point1.x;
  1429. var y1 = point2.y - point1.y;
  1430. var z1 = point2.z - point1.z;
  1431. var x2 = point3.x - point1.x;
  1432. var y2 = point3.y - point1.y;
  1433. var z2 = point3.z - point1.z;
  1434. var yz = (y1 * z2) - (z1 * y2);
  1435. var xz = (z1 * x2) - (x1 * z2);
  1436. var xy = (x1 * y2) - (y1 * x2);
  1437. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1438. var invPyth;
  1439. if (pyth != 0) {
  1440. invPyth = 1.0 / pyth;
  1441. } else {
  1442. invPyth = 0;
  1443. }
  1444. this.normal.x = yz * invPyth;
  1445. this.normal.y = xz * invPyth;
  1446. this.normal.z = xy * invPyth;
  1447. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1448. };
  1449. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1450. var dot = Vector3.Dot(this.normal, direction);
  1451. return (dot <= epsilon);
  1452. };
  1453. Plane.prototype.signedDistanceTo = function (point) {
  1454. return Vector3.Dot(point, this.normal) + this.d;
  1455. };
  1456. Plane.FromArray = function (array) {
  1457. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1458. };
  1459. Plane.FromPoints = function (point1, point2, point3) {
  1460. var result = new BABYLON.Plane(0, 0, 0, 0);
  1461. result.copyFromPoints(point1, point2, point3);
  1462. return result;
  1463. };
  1464. Plane.FromPositionAndNormal = function (origin, normal) {
  1465. var result = new BABYLON.Plane(0, 0, 0, 0);
  1466. normal.normalize();
  1467. result.normal = normal;
  1468. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1469. return result;
  1470. };
  1471. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1472. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1473. return Vector3.Dot(point, normal) + d;
  1474. };
  1475. return Plane;
  1476. })();
  1477. BABYLON.Plane = Plane;
  1478. var Viewport = (function () {
  1479. function Viewport(x, y, width, height) {
  1480. this.x = x;
  1481. this.y = y;
  1482. this.width = width;
  1483. this.height = height;
  1484. }
  1485. Viewport.prototype.toGlobal = function (engine) {
  1486. var width = engine.getRenderWidth();
  1487. var height = engine.getRenderHeight();
  1488. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1489. };
  1490. return Viewport;
  1491. })();
  1492. BABYLON.Viewport = Viewport;
  1493. var Frustum = (function () {
  1494. function Frustum() {
  1495. }
  1496. Frustum.GetPlanes = function (transform) {
  1497. var frustumPlanes = [];
  1498. for (var index = 0; index < 6; index++) {
  1499. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1500. }
  1501. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1502. return frustumPlanes;
  1503. };
  1504. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1505. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1506. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1507. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1508. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1509. frustumPlanes[0].normalize();
  1510. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1511. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1512. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1513. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1514. frustumPlanes[1].normalize();
  1515. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1516. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1517. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1518. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1519. frustumPlanes[2].normalize();
  1520. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1521. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1522. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1523. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1524. frustumPlanes[3].normalize();
  1525. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1526. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1527. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1528. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1529. frustumPlanes[4].normalize();
  1530. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1531. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1532. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1533. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1534. frustumPlanes[5].normalize();
  1535. };
  1536. return Frustum;
  1537. })();
  1538. BABYLON.Frustum = Frustum;
  1539. var Ray = (function () {
  1540. function Ray(origin, direction) {
  1541. this.origin = origin;
  1542. this.direction = direction;
  1543. }
  1544. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1545. var d = 0.0;
  1546. var maxValue = Number.MAX_VALUE;
  1547. if (Math.abs(this.direction.x) < 0.0000001) {
  1548. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1549. return false;
  1550. }
  1551. } else {
  1552. var inv = 1.0 / this.direction.x;
  1553. var min = (minimum.x - this.origin.x) * inv;
  1554. var max = (maximum.x - this.origin.x) * inv;
  1555. if (min > max) {
  1556. var temp = min;
  1557. min = max;
  1558. max = temp;
  1559. }
  1560. d = Math.max(min, d);
  1561. maxValue = Math.min(max, maxValue);
  1562. if (d > maxValue) {
  1563. return false;
  1564. }
  1565. }
  1566. if (Math.abs(this.direction.y) < 0.0000001) {
  1567. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1568. return false;
  1569. }
  1570. } else {
  1571. inv = 1.0 / this.direction.y;
  1572. min = (minimum.y - this.origin.y) * inv;
  1573. max = (maximum.y - this.origin.y) * inv;
  1574. if (min > max) {
  1575. temp = min;
  1576. min = max;
  1577. max = temp;
  1578. }
  1579. d = Math.max(min, d);
  1580. maxValue = Math.min(max, maxValue);
  1581. if (d > maxValue) {
  1582. return false;
  1583. }
  1584. }
  1585. if (Math.abs(this.direction.z) < 0.0000001) {
  1586. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1587. return false;
  1588. }
  1589. } else {
  1590. inv = 1.0 / this.direction.z;
  1591. min = (minimum.z - this.origin.z) * inv;
  1592. max = (maximum.z - this.origin.z) * inv;
  1593. if (min > max) {
  1594. temp = min;
  1595. min = max;
  1596. max = temp;
  1597. }
  1598. d = Math.max(min, d);
  1599. maxValue = Math.min(max, maxValue);
  1600. if (d > maxValue) {
  1601. return false;
  1602. }
  1603. }
  1604. return true;
  1605. };
  1606. Ray.prototype.intersectsBox = function (box) {
  1607. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1608. };
  1609. Ray.prototype.intersectsSphere = function (sphere) {
  1610. var x = sphere.center.x - this.origin.x;
  1611. var y = sphere.center.y - this.origin.y;
  1612. var z = sphere.center.z - this.origin.z;
  1613. var pyth = (x * x) + (y * y) + (z * z);
  1614. var rr = sphere.radius * sphere.radius;
  1615. if (pyth <= rr) {
  1616. return true;
  1617. }
  1618. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1619. if (dot < 0.0) {
  1620. return false;
  1621. }
  1622. var temp = pyth - (dot * dot);
  1623. return temp <= rr;
  1624. };
  1625. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1626. if (!this._edge1) {
  1627. this._edge1 = BABYLON.Vector3.Zero();
  1628. this._edge2 = BABYLON.Vector3.Zero();
  1629. this._pvec = BABYLON.Vector3.Zero();
  1630. this._tvec = BABYLON.Vector3.Zero();
  1631. this._qvec = BABYLON.Vector3.Zero();
  1632. }
  1633. vertex1.subtractToRef(vertex0, this._edge1);
  1634. vertex2.subtractToRef(vertex0, this._edge2);
  1635. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1636. var det = Vector3.Dot(this._edge1, this._pvec);
  1637. if (det === 0) {
  1638. return null;
  1639. }
  1640. var invdet = 1 / det;
  1641. this.origin.subtractToRef(vertex0, this._tvec);
  1642. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1643. if (bu < 0 || bu > 1.0) {
  1644. return null;
  1645. }
  1646. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1647. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1648. if (bv < 0 || bu + bv > 1.0) {
  1649. return null;
  1650. }
  1651. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1652. };
  1653. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1654. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1655. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1656. var direction = end.subtract(start);
  1657. direction.normalize();
  1658. return new Ray(start, direction);
  1659. };
  1660. Ray.Transform = function (ray, matrix) {
  1661. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1662. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1663. return new Ray(newOrigin, newDirection);
  1664. };
  1665. return Ray;
  1666. })();
  1667. BABYLON.Ray = Ray;
  1668. (function (Space) {
  1669. Space[Space["LOCAL"] = 0] = "LOCAL";
  1670. Space[Space["WORLD"] = 1] = "WORLD";
  1671. })(BABYLON.Space || (BABYLON.Space = {}));
  1672. var Space = BABYLON.Space;
  1673. var Axis = (function () {
  1674. function Axis() {
  1675. }
  1676. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1677. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1678. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1679. return Axis;
  1680. })();
  1681. BABYLON.Axis = Axis;
  1682. ;
  1683. })(BABYLON || (BABYLON = {}));
  1684. var BABYLON;
  1685. (function (BABYLON) {
  1686. var screenshotCanvas;
  1687. var fpsRange = 60;
  1688. var previousFramesDuration = [];
  1689. var fps = 60;
  1690. var deltaTime = 0;
  1691. var cloneValue = function (source, destinationObject) {
  1692. if (!source)
  1693. return null;
  1694. if (source instanceof BABYLON.Mesh) {
  1695. return null;
  1696. }
  1697. if (source instanceof BABYLON.SubMesh) {
  1698. return source.clone(destinationObject);
  1699. } else if (source.clone) {
  1700. return source.clone();
  1701. }
  1702. return null;
  1703. };
  1704. var Tools = (function () {
  1705. function Tools() {
  1706. }
  1707. Tools.GetFilename = function (path) {
  1708. var index = path.lastIndexOf("/");
  1709. if (index < 0)
  1710. return path;
  1711. return path.substring(index + 1);
  1712. };
  1713. Tools.GetDOMTextContent = function (element) {
  1714. var result = "";
  1715. var child = element.firstChild;
  1716. while (child) {
  1717. if (child.nodeType == 3) {
  1718. result += child.textContent;
  1719. }
  1720. child = child.nextSibling;
  1721. }
  1722. return result;
  1723. };
  1724. Tools.ToDegrees = function (angle) {
  1725. return angle * 180 / Math.PI;
  1726. };
  1727. Tools.ToRadians = function (angle) {
  1728. return angle * Math.PI / 180;
  1729. };
  1730. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1731. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1732. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1733. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1734. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1735. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1736. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1737. }
  1738. return {
  1739. minimum: minimum,
  1740. maximum: maximum
  1741. };
  1742. };
  1743. Tools.ExtractMinAndMax = function (positions, start, count) {
  1744. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1745. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1746. for (var index = start; index < start + count; index++) {
  1747. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1748. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1749. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1750. }
  1751. return {
  1752. minimum: minimum,
  1753. maximum: maximum
  1754. };
  1755. };
  1756. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1757. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1758. return undefined;
  1759. return Array.isArray(obj) ? obj : [obj];
  1760. };
  1761. Tools.GetPointerPrefix = function () {
  1762. var eventPrefix = "pointer";
  1763. if (!navigator.pointerEnabled) {
  1764. eventPrefix = "mouse";
  1765. }
  1766. return eventPrefix;
  1767. };
  1768. Tools.QueueNewFrame = function (func) {
  1769. if (window.requestAnimationFrame)
  1770. window.requestAnimationFrame(func);
  1771. else if (window.msRequestAnimationFrame)
  1772. window.msRequestAnimationFrame(func);
  1773. else if (window.webkitRequestAnimationFrame)
  1774. window.webkitRequestAnimationFrame(func);
  1775. else if (window.mozRequestAnimationFrame)
  1776. window.mozRequestAnimationFrame(func);
  1777. else if (window.oRequestAnimationFrame)
  1778. window.oRequestAnimationFrame(func);
  1779. else {
  1780. window.setTimeout(func, 16);
  1781. }
  1782. };
  1783. Tools.RequestFullscreen = function (element) {
  1784. if (element.requestFullscreen)
  1785. element.requestFullscreen();
  1786. else if (element.msRequestFullscreen)
  1787. element.msRequestFullscreen();
  1788. else if (element.webkitRequestFullscreen)
  1789. element.webkitRequestFullscreen();
  1790. else if (element.mozRequestFullScreen)
  1791. element.mozRequestFullScreen();
  1792. };
  1793. Tools.ExitFullscreen = function () {
  1794. if (document.exitFullscreen) {
  1795. document.exitFullscreen();
  1796. } else if (document.mozCancelFullScreen) {
  1797. document.mozCancelFullScreen();
  1798. } else if (document.webkitCancelFullScreen) {
  1799. document.webkitCancelFullScreen();
  1800. } else if (document.msCancelFullScreen) {
  1801. document.msCancelFullScreen();
  1802. }
  1803. };
  1804. Tools.CleanUrl = function (url) {
  1805. url = url.replace(/#/mg, "%23");
  1806. return url;
  1807. };
  1808. Tools.LoadImage = function (url, onload, onerror, database) {
  1809. url = Tools.CleanUrl(url);
  1810. var img = new Image();
  1811. img.crossOrigin = 'anonymous';
  1812. img.onload = function () {
  1813. onload(img);
  1814. };
  1815. img.onerror = function (err) {
  1816. onerror(img, err);
  1817. };
  1818. var noIndexedDB = function () {
  1819. img.src = url;
  1820. };
  1821. var loadFromIndexedDB = function () {
  1822. database.loadImageFromDB(url, img);
  1823. };
  1824. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1825. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1826. } else {
  1827. if (url.indexOf("file:") === -1) {
  1828. noIndexedDB();
  1829. } else {
  1830. try {
  1831. var textureName = url.substring(5);
  1832. var blobURL;
  1833. try {
  1834. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1835. } catch (ex) {
  1836. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1837. }
  1838. img.src = blobURL;
  1839. } catch (e) {
  1840. Tools.Log("Error while trying to load texture: " + textureName);
  1841. img.src = null;
  1842. }
  1843. }
  1844. }
  1845. return img;
  1846. };
  1847. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1848. url = Tools.CleanUrl(url);
  1849. var noIndexedDB = function () {
  1850. var request = new XMLHttpRequest();
  1851. var loadUrl = Tools.BaseUrl + url;
  1852. request.open('GET', loadUrl, true);
  1853. if (useArrayBuffer) {
  1854. request.responseType = "arraybuffer";
  1855. }
  1856. request.onprogress = progressCallBack;
  1857. request.onreadystatechange = function () {
  1858. if (request.readyState == 4) {
  1859. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1860. callback(!useArrayBuffer ? request.responseText : request.response);
  1861. } else {
  1862. if (onError) {
  1863. onError();
  1864. } else {
  1865. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1866. }
  1867. }
  1868. }
  1869. };
  1870. request.send(null);
  1871. };
  1872. var loadFromIndexedDB = function () {
  1873. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1874. };
  1875. if (url.indexOf("file:") !== -1) {
  1876. var fileName = url.substring(5);
  1877. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1878. } else {
  1879. if (database && database.enableSceneOffline) {
  1880. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1881. } else {
  1882. noIndexedDB();
  1883. }
  1884. }
  1885. };
  1886. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1887. var reader = new FileReader();
  1888. reader.onload = function (e) {
  1889. callback(e.target.result);
  1890. };
  1891. reader.onprogress = progressCallBack;
  1892. if (!useArrayBuffer) {
  1893. reader.readAsText(fileToLoad);
  1894. } else {
  1895. reader.readAsArrayBuffer(fileToLoad);
  1896. }
  1897. };
  1898. Tools.CheckExtends = function (v, min, max) {
  1899. if (v.x < min.x)
  1900. min.x = v.x;
  1901. if (v.y < min.y)
  1902. min.y = v.y;
  1903. if (v.z < min.z)
  1904. min.z = v.z;
  1905. if (v.x > max.x)
  1906. max.x = v.x;
  1907. if (v.y > max.y)
  1908. max.y = v.y;
  1909. if (v.z > max.z)
  1910. max.z = v.z;
  1911. };
  1912. Tools.WithinEpsilon = function (a, b) {
  1913. var num = a - b;
  1914. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1915. };
  1916. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1917. for (var prop in source) {
  1918. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1919. continue;
  1920. }
  1921. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1922. continue;
  1923. }
  1924. var sourceValue = source[prop];
  1925. var typeOfSourceValue = typeof sourceValue;
  1926. if (typeOfSourceValue == "function") {
  1927. continue;
  1928. }
  1929. if (typeOfSourceValue == "object") {
  1930. if (sourceValue instanceof Array) {
  1931. destination[prop] = [];
  1932. if (sourceValue.length > 0) {
  1933. if (typeof sourceValue[0] == "object") {
  1934. for (var index = 0; index < sourceValue.length; index++) {
  1935. var clonedValue = cloneValue(sourceValue[index], destination);
  1936. if (destination[prop].indexOf(clonedValue) === -1) {
  1937. destination[prop].push(clonedValue);
  1938. }
  1939. }
  1940. } else {
  1941. destination[prop] = sourceValue.slice(0);
  1942. }
  1943. }
  1944. } else {
  1945. destination[prop] = cloneValue(sourceValue, destination);
  1946. }
  1947. } else {
  1948. destination[prop] = sourceValue;
  1949. }
  1950. }
  1951. };
  1952. Tools.IsEmpty = function (obj) {
  1953. for (var i in obj) {
  1954. return false;
  1955. }
  1956. return true;
  1957. };
  1958. Tools.RegisterTopRootEvents = function (events) {
  1959. for (var index = 0; index < events.length; index++) {
  1960. var event = events[index];
  1961. window.addEventListener(event.name, event.handler, false);
  1962. try {
  1963. if (window.parent) {
  1964. window.parent.addEventListener(event.name, event.handler, false);
  1965. }
  1966. } catch (e) {
  1967. }
  1968. }
  1969. };
  1970. Tools.UnregisterTopRootEvents = function (events) {
  1971. for (var index = 0; index < events.length; index++) {
  1972. var event = events[index];
  1973. window.removeEventListener(event.name, event.handler);
  1974. try {
  1975. if (window.parent) {
  1976. window.parent.removeEventListener(event.name, event.handler);
  1977. }
  1978. } catch (e) {
  1979. }
  1980. }
  1981. };
  1982. Tools.GetFps = function () {
  1983. return fps;
  1984. };
  1985. Tools.GetDeltaTime = function () {
  1986. return deltaTime;
  1987. };
  1988. Tools._MeasureFps = function () {
  1989. previousFramesDuration.push((new Date).getTime());
  1990. var length = previousFramesDuration.length;
  1991. if (length >= 2) {
  1992. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  1993. }
  1994. if (length >= fpsRange) {
  1995. if (length > fpsRange) {
  1996. previousFramesDuration.splice(0, 1);
  1997. length = previousFramesDuration.length;
  1998. }
  1999. var sum = 0;
  2000. for (var id = 0; id < length - 1; id++) {
  2001. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2002. }
  2003. fps = 1000.0 / (sum / (length - 1));
  2004. }
  2005. };
  2006. Tools.CreateScreenshot = function (engine, camera, size) {
  2007. var width;
  2008. var height;
  2009. var scene = camera.getScene();
  2010. var previousCamera = null;
  2011. if (scene.activeCamera !== camera) {
  2012. previousCamera = scene.activeCamera;
  2013. scene.activeCamera = camera;
  2014. }
  2015. if (size.precision) {
  2016. width = Math.round(engine.getRenderWidth() * size.precision);
  2017. height = Math.round(width / engine.getAspectRatio(camera));
  2018. size = { width: width, height: height };
  2019. } else if (size.width && size.height) {
  2020. width = size.width;
  2021. height = size.height;
  2022. } else if (size.width && !size.height) {
  2023. width = size.width;
  2024. height = Math.round(width / engine.getAspectRatio(camera));
  2025. size = { width: width, height: height };
  2026. } else if (size.height && !size.width) {
  2027. height = size.height;
  2028. width = Math.round(height * engine.getAspectRatio(camera));
  2029. size = { width: width, height: height };
  2030. } else if (!isNaN(size)) {
  2031. height = size;
  2032. width = size;
  2033. } else {
  2034. Tools.Error("Invalid 'size' parameter !");
  2035. return;
  2036. }
  2037. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2038. texture.renderList = engine.scenes[0].meshes;
  2039. texture.onAfterRender = function () {
  2040. var numberOfChannelsByLine = width * 4;
  2041. var halfHeight = height / 2;
  2042. var data = engine.readPixels(0, 0, width, height);
  2043. for (var i = 0; i < halfHeight; i++) {
  2044. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2045. var currentCell = j + i * numberOfChannelsByLine;
  2046. var targetLine = height - i - 1;
  2047. var targetCell = j + targetLine * numberOfChannelsByLine;
  2048. var temp = data[currentCell];
  2049. data[currentCell] = data[targetCell];
  2050. data[targetCell] = temp;
  2051. }
  2052. }
  2053. if (!screenshotCanvas) {
  2054. screenshotCanvas = document.createElement('canvas');
  2055. }
  2056. screenshotCanvas.width = width;
  2057. screenshotCanvas.height = height;
  2058. var context = screenshotCanvas.getContext('2d');
  2059. var imageData = context.createImageData(width, height);
  2060. imageData.data.set(data);
  2061. context.putImageData(imageData, 0, 0);
  2062. var base64Image = screenshotCanvas.toDataURL();
  2063. if (("download" in document.createElement("a"))) {
  2064. var a = window.document.createElement("a");
  2065. a.href = base64Image;
  2066. var date = new Date();
  2067. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2068. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2069. window.document.body.appendChild(a);
  2070. a.addEventListener("click", function () {
  2071. a.parentElement.removeChild(a);
  2072. });
  2073. a.click();
  2074. } else {
  2075. var newWindow = window.open("");
  2076. var img = newWindow.document.createElement("img");
  2077. img.src = base64Image;
  2078. newWindow.document.body.appendChild(img);
  2079. }
  2080. };
  2081. texture.render(true);
  2082. texture.dispose();
  2083. if (previousCamera) {
  2084. scene.activeCamera = previousCamera;
  2085. }
  2086. };
  2087. Tools.ValidateXHRData = function (xhr, dataType) {
  2088. if (typeof dataType === "undefined") { dataType = 7; }
  2089. try {
  2090. if (dataType & 1) {
  2091. if (xhr.responseText && xhr.responseText.length > 0) {
  2092. return true;
  2093. } else if (dataType === 1) {
  2094. return false;
  2095. }
  2096. }
  2097. if (dataType & 2) {
  2098. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2099. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2100. return true;
  2101. } else if (dataType === 2) {
  2102. return false;
  2103. }
  2104. }
  2105. if (dataType & 4) {
  2106. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2107. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2108. return true;
  2109. } else {
  2110. return false;
  2111. }
  2112. }
  2113. } catch (e) {
  2114. }
  2115. return false;
  2116. };
  2117. Object.defineProperty(Tools, "NoneLogLevel", {
  2118. get: function () {
  2119. return Tools._NoneLogLevel;
  2120. },
  2121. enumerable: true,
  2122. configurable: true
  2123. });
  2124. Object.defineProperty(Tools, "MessageLogLevel", {
  2125. get: function () {
  2126. return Tools._MessageLogLevel;
  2127. },
  2128. enumerable: true,
  2129. configurable: true
  2130. });
  2131. Object.defineProperty(Tools, "WarningLogLevel", {
  2132. get: function () {
  2133. return Tools._WarningLogLevel;
  2134. },
  2135. enumerable: true,
  2136. configurable: true
  2137. });
  2138. Object.defineProperty(Tools, "ErrorLogLevel", {
  2139. get: function () {
  2140. return Tools._ErrorLogLevel;
  2141. },
  2142. enumerable: true,
  2143. configurable: true
  2144. });
  2145. Object.defineProperty(Tools, "AllLogLevel", {
  2146. get: function () {
  2147. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2148. },
  2149. enumerable: true,
  2150. configurable: true
  2151. });
  2152. Tools._FormatMessage = function (message) {
  2153. var padStr = function (i) {
  2154. return (i < 10) ? "0" + i : "" + i;
  2155. };
  2156. var date = new Date();
  2157. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2158. };
  2159. Tools._LogDisabled = function (message) {
  2160. };
  2161. Tools._LogEnabled = function (message) {
  2162. console.log(Tools._FormatMessage(message));
  2163. };
  2164. Tools._WarnDisabled = function (message) {
  2165. };
  2166. Tools._WarnEnabled = function (message) {
  2167. console.warn(Tools._FormatMessage(message));
  2168. };
  2169. Tools._ErrorDisabled = function (message) {
  2170. };
  2171. Tools._ErrorEnabled = function (message) {
  2172. console.error(Tools._FormatMessage(message));
  2173. };
  2174. Object.defineProperty(Tools, "LogLevels", {
  2175. set: function (level) {
  2176. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2177. Tools.Log = Tools._LogEnabled;
  2178. } else {
  2179. Tools.Log = Tools._LogDisabled;
  2180. }
  2181. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2182. Tools.Warn = Tools._WarnEnabled;
  2183. } else {
  2184. Tools.Warn = Tools._WarnDisabled;
  2185. }
  2186. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2187. Tools.Error = Tools._ErrorEnabled;
  2188. } else {
  2189. Tools.Error = Tools._ErrorDisabled;
  2190. }
  2191. },
  2192. enumerable: true,
  2193. configurable: true
  2194. });
  2195. Tools.BaseUrl = "";
  2196. Tools._NoneLogLevel = 0;
  2197. Tools._MessageLogLevel = 1;
  2198. Tools._WarningLogLevel = 2;
  2199. Tools._ErrorLogLevel = 4;
  2200. Tools.Log = Tools._LogEnabled;
  2201. Tools.Warn = Tools._WarnEnabled;
  2202. Tools.Error = Tools._ErrorEnabled;
  2203. return Tools;
  2204. })();
  2205. BABYLON.Tools = Tools;
  2206. })(BABYLON || (BABYLON = {}));
  2207. var BABYLON;
  2208. (function (BABYLON) {
  2209. var _DepthCullingState = (function () {
  2210. function _DepthCullingState() {
  2211. this._isDepthTestDirty = false;
  2212. this._isDepthMaskDirty = false;
  2213. this._isDepthFuncDirty = false;
  2214. this._isCullFaceDirty = false;
  2215. this._isCullDirty = false;
  2216. }
  2217. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2218. get: function () {
  2219. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2220. },
  2221. enumerable: true,
  2222. configurable: true
  2223. });
  2224. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2225. get: function () {
  2226. return this._cullFace;
  2227. },
  2228. set: function (value) {
  2229. if (this._cullFace === value) {
  2230. return;
  2231. }
  2232. this._cullFace = value;
  2233. this._isCullFaceDirty = true;
  2234. },
  2235. enumerable: true,
  2236. configurable: true
  2237. });
  2238. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2239. get: function () {
  2240. return this._cull;
  2241. },
  2242. set: function (value) {
  2243. if (this._cull === value) {
  2244. return;
  2245. }
  2246. this._cull = value;
  2247. this._isCullDirty = true;
  2248. },
  2249. enumerable: true,
  2250. configurable: true
  2251. });
  2252. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2253. get: function () {
  2254. return this._depthFunc;
  2255. },
  2256. set: function (value) {
  2257. if (this._depthFunc === value) {
  2258. return;
  2259. }
  2260. this._depthFunc = value;
  2261. this._isDepthFuncDirty = true;
  2262. },
  2263. enumerable: true,
  2264. configurable: true
  2265. });
  2266. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2267. get: function () {
  2268. return this._depthMask;
  2269. },
  2270. set: function (value) {
  2271. if (this._depthMask === value) {
  2272. return;
  2273. }
  2274. this._depthMask = value;
  2275. this._isDepthMaskDirty = true;
  2276. },
  2277. enumerable: true,
  2278. configurable: true
  2279. });
  2280. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2281. get: function () {
  2282. return this._depthTest;
  2283. },
  2284. set: function (value) {
  2285. if (this._depthTest === value) {
  2286. return;
  2287. }
  2288. this._depthTest = value;
  2289. this._isDepthTestDirty = true;
  2290. },
  2291. enumerable: true,
  2292. configurable: true
  2293. });
  2294. _DepthCullingState.prototype.reset = function () {
  2295. this._depthMask = true;
  2296. this._depthTest = true;
  2297. this._depthFunc = null;
  2298. this._cull = null;
  2299. this._cullFace = null;
  2300. this._isDepthTestDirty = true;
  2301. this._isDepthMaskDirty = true;
  2302. this._isDepthFuncDirty = false;
  2303. this._isCullFaceDirty = false;
  2304. this._isCullDirty = false;
  2305. };
  2306. _DepthCullingState.prototype.apply = function (gl) {
  2307. if (!this.isDirty) {
  2308. return;
  2309. }
  2310. if (this._isCullDirty) {
  2311. if (this.cull === true) {
  2312. gl.enable(gl.CULL_FACE);
  2313. } else if (this.cull === false) {
  2314. gl.disable(gl.CULL_FACE);
  2315. }
  2316. this._isCullDirty = false;
  2317. }
  2318. if (this._isCullFaceDirty) {
  2319. gl.cullFace(this.cullFace);
  2320. this._isCullFaceDirty = false;
  2321. }
  2322. if (this._isDepthMaskDirty) {
  2323. gl.depthMask(this.depthMask);
  2324. this._isDepthMaskDirty = false;
  2325. }
  2326. if (this._isDepthTestDirty) {
  2327. if (this.depthTest === true) {
  2328. gl.enable(gl.DEPTH_TEST);
  2329. } else if (this.depthTest === false) {
  2330. gl.disable(gl.DEPTH_TEST);
  2331. }
  2332. this._isDepthTestDirty = false;
  2333. }
  2334. if (this._isDepthFuncDirty) {
  2335. gl.depthFunc(this.depthFunc);
  2336. this._isDepthFuncDirty = false;
  2337. }
  2338. };
  2339. return _DepthCullingState;
  2340. })();
  2341. BABYLON._DepthCullingState = _DepthCullingState;
  2342. var _AlphaState = (function () {
  2343. function _AlphaState() {
  2344. this._isAlphaBlendDirty = false;
  2345. this._isBlendFunctionParametersDirty = false;
  2346. this._alphaBlend = false;
  2347. this._blendFunctionParameters = new Array(4);
  2348. }
  2349. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2350. get: function () {
  2351. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2352. },
  2353. enumerable: true,
  2354. configurable: true
  2355. });
  2356. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2357. get: function () {
  2358. return this._alphaBlend;
  2359. },
  2360. set: function (value) {
  2361. if (this._alphaBlend === value) {
  2362. return;
  2363. }
  2364. this._alphaBlend = value;
  2365. this._isAlphaBlendDirty = true;
  2366. },
  2367. enumerable: true,
  2368. configurable: true
  2369. });
  2370. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2371. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2372. return;
  2373. }
  2374. this._blendFunctionParameters[0] = value0;
  2375. this._blendFunctionParameters[1] = value1;
  2376. this._blendFunctionParameters[2] = value2;
  2377. this._blendFunctionParameters[3] = value3;
  2378. this._isBlendFunctionParametersDirty = true;
  2379. };
  2380. _AlphaState.prototype.reset = function () {
  2381. this._alphaBlend = false;
  2382. this._blendFunctionParameters[0] = null;
  2383. this._blendFunctionParameters[1] = null;
  2384. this._blendFunctionParameters[2] = null;
  2385. this._blendFunctionParameters[3] = null;
  2386. this._isAlphaBlendDirty = true;
  2387. this._isBlendFunctionParametersDirty = false;
  2388. };
  2389. _AlphaState.prototype.apply = function (gl) {
  2390. if (!this.isDirty) {
  2391. return;
  2392. }
  2393. if (this._isAlphaBlendDirty) {
  2394. if (this._alphaBlend === true) {
  2395. gl.enable(gl.BLEND);
  2396. } else if (this._alphaBlend === false) {
  2397. gl.disable(gl.BLEND);
  2398. }
  2399. this._isAlphaBlendDirty = false;
  2400. }
  2401. if (this._isBlendFunctionParametersDirty) {
  2402. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2403. this._isBlendFunctionParametersDirty = false;
  2404. }
  2405. };
  2406. return _AlphaState;
  2407. })();
  2408. BABYLON._AlphaState = _AlphaState;
  2409. var compileShader = function (gl, source, type, defines) {
  2410. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2411. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2412. gl.compileShader(shader);
  2413. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2414. throw new Error(gl.getShaderInfoLog(shader));
  2415. }
  2416. return shader;
  2417. };
  2418. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2419. var magFilter = gl.NEAREST;
  2420. var minFilter = gl.NEAREST;
  2421. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2422. magFilter = gl.LINEAR;
  2423. if (generateMipMaps) {
  2424. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2425. } else {
  2426. minFilter = gl.LINEAR;
  2427. }
  2428. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2429. magFilter = gl.LINEAR;
  2430. if (generateMipMaps) {
  2431. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2432. } else {
  2433. minFilter = gl.LINEAR;
  2434. }
  2435. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2436. magFilter = gl.NEAREST;
  2437. if (generateMipMaps) {
  2438. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2439. } else {
  2440. minFilter = gl.NEAREST;
  2441. }
  2442. }
  2443. return {
  2444. min: minFilter,
  2445. mag: magFilter
  2446. };
  2447. };
  2448. var getExponantOfTwo = function (value, max) {
  2449. var count = 1;
  2450. do {
  2451. count *= 2;
  2452. } while(count < value);
  2453. if (count > max)
  2454. count = max;
  2455. return count;
  2456. };
  2457. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2458. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2459. var engine = scene.getEngine();
  2460. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2461. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2462. gl.bindTexture(gl.TEXTURE_2D, texture);
  2463. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2464. processFunction(potWidth, potHeight);
  2465. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2468. if (!noMipmap && !isCompressed) {
  2469. gl.generateMipmap(gl.TEXTURE_2D);
  2470. }
  2471. gl.bindTexture(gl.TEXTURE_2D, null);
  2472. engine._activeTexturesCache = [];
  2473. texture._baseWidth = width;
  2474. texture._baseHeight = height;
  2475. texture._width = potWidth;
  2476. texture._height = potHeight;
  2477. texture.isReady = true;
  2478. scene._removePendingData(texture);
  2479. };
  2480. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2481. var img;
  2482. var onload = function () {
  2483. loadedImages.push(img);
  2484. scene._removePendingData(img);
  2485. if (index != extensions.length - 1) {
  2486. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2487. } else {
  2488. onfinish(loadedImages);
  2489. }
  2490. };
  2491. var onerror = function () {
  2492. scene._removePendingData(img);
  2493. };
  2494. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2495. scene._addPendingData(img);
  2496. };
  2497. var EngineCapabilities = (function () {
  2498. function EngineCapabilities() {
  2499. }
  2500. return EngineCapabilities;
  2501. })();
  2502. BABYLON.EngineCapabilities = EngineCapabilities;
  2503. var Engine = (function () {
  2504. function Engine(canvas, antialias, options) {
  2505. var _this = this;
  2506. this.isFullscreen = false;
  2507. this.isPointerLock = false;
  2508. this.forceWireframe = false;
  2509. this.cullBackFaces = true;
  2510. this.renderEvenInBackground = true;
  2511. this.scenes = new Array();
  2512. this._windowIsBackground = false;
  2513. this._runningLoop = false;
  2514. this._loadingDivBackgroundColor = "black";
  2515. this._depthCullingState = new _DepthCullingState();
  2516. this._alphaState = new _AlphaState();
  2517. this._loadedTexturesCache = new Array();
  2518. this._activeTexturesCache = new Array();
  2519. this._compiledEffects = {};
  2520. this._renderingCanvas = canvas;
  2521. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2522. options = options || {};
  2523. options.antialias = antialias;
  2524. try {
  2525. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2526. } catch (e) {
  2527. throw new Error("WebGL not supported");
  2528. }
  2529. if (!this._gl) {
  2530. throw new Error("WebGL not supported");
  2531. }
  2532. this._onBlur = function () {
  2533. _this._windowIsBackground = true;
  2534. };
  2535. this._onFocus = function () {
  2536. _this._windowIsBackground = false;
  2537. };
  2538. window.addEventListener("blur", this._onBlur);
  2539. window.addEventListener("focus", this._onFocus);
  2540. this._workingCanvas = document.createElement("canvas");
  2541. this._workingContext = this._workingCanvas.getContext("2d");
  2542. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2543. this.resize();
  2544. this._caps = new EngineCapabilities();
  2545. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2546. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2547. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2548. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2549. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2550. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2551. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2552. 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');
  2553. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2554. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2555. this.setDepthBuffer(true);
  2556. this.setDepthFunctionToLessOrEqual();
  2557. this.setDepthWrite(true);
  2558. this._onFullscreenChange = function () {
  2559. if (document.fullscreen !== undefined) {
  2560. _this.isFullscreen = document.fullscreen;
  2561. } else if (document.mozFullScreen !== undefined) {
  2562. _this.isFullscreen = document.mozFullScreen;
  2563. } else if (document.webkitIsFullScreen !== undefined) {
  2564. _this.isFullscreen = document.webkitIsFullScreen;
  2565. } else if (document.msIsFullScreen !== undefined) {
  2566. _this.isFullscreen = document.msIsFullScreen;
  2567. }
  2568. if (_this.isFullscreen && _this._pointerLockRequested) {
  2569. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2570. if (canvas.requestPointerLock) {
  2571. canvas.requestPointerLock();
  2572. }
  2573. }
  2574. };
  2575. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2576. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2577. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2578. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2579. this._onPointerLockChange = function () {
  2580. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2581. };
  2582. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2583. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2584. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2585. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2586. }
  2587. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2588. get: function () {
  2589. return Engine._ALPHA_DISABLE;
  2590. },
  2591. enumerable: true,
  2592. configurable: true
  2593. });
  2594. Object.defineProperty(Engine, "ALPHA_ADD", {
  2595. get: function () {
  2596. return Engine._ALPHA_ADD;
  2597. },
  2598. enumerable: true,
  2599. configurable: true
  2600. });
  2601. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2602. get: function () {
  2603. return Engine._ALPHA_COMBINE;
  2604. },
  2605. enumerable: true,
  2606. configurable: true
  2607. });
  2608. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2609. get: function () {
  2610. return Engine._DELAYLOADSTATE_NONE;
  2611. },
  2612. enumerable: true,
  2613. configurable: true
  2614. });
  2615. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2616. get: function () {
  2617. return Engine._DELAYLOADSTATE_LOADED;
  2618. },
  2619. enumerable: true,
  2620. configurable: true
  2621. });
  2622. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2623. get: function () {
  2624. return Engine._DELAYLOADSTATE_LOADING;
  2625. },
  2626. enumerable: true,
  2627. configurable: true
  2628. });
  2629. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2630. get: function () {
  2631. return Engine._DELAYLOADSTATE_NOTLOADED;
  2632. },
  2633. enumerable: true,
  2634. configurable: true
  2635. });
  2636. Object.defineProperty(Engine, "Version", {
  2637. get: function () {
  2638. return "1.14.0";
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Engine.prototype.getAspectRatio = function (camera) {
  2644. var viewport = camera.viewport;
  2645. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2646. };
  2647. Engine.prototype.getRenderWidth = function () {
  2648. if (this._currentRenderTarget) {
  2649. return this._currentRenderTarget._width;
  2650. }
  2651. return this._renderingCanvas.width;
  2652. };
  2653. Engine.prototype.getRenderHeight = function () {
  2654. if (this._currentRenderTarget) {
  2655. return this._currentRenderTarget._height;
  2656. }
  2657. return this._renderingCanvas.height;
  2658. };
  2659. Engine.prototype.getRenderingCanvas = function () {
  2660. return this._renderingCanvas;
  2661. };
  2662. Engine.prototype.getRenderingCanvasClientRect = function () {
  2663. return this._renderingCanvas.getBoundingClientRect();
  2664. };
  2665. Engine.prototype.setHardwareScalingLevel = function (level) {
  2666. this._hardwareScalingLevel = level;
  2667. this.resize();
  2668. };
  2669. Engine.prototype.getHardwareScalingLevel = function () {
  2670. return this._hardwareScalingLevel;
  2671. };
  2672. Engine.prototype.getLoadedTexturesCache = function () {
  2673. return this._loadedTexturesCache;
  2674. };
  2675. Engine.prototype.getCaps = function () {
  2676. return this._caps;
  2677. };
  2678. Engine.prototype.setDepthFunctionToGreater = function () {
  2679. this._depthCullingState.depthFunc = this._gl.GREATER;
  2680. };
  2681. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2682. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2683. };
  2684. Engine.prototype.setDepthFunctionToLess = function () {
  2685. this._depthCullingState.depthFunc = this._gl.LESS;
  2686. };
  2687. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2688. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2689. };
  2690. Engine.prototype.stopRenderLoop = function () {
  2691. this._renderFunction = null;
  2692. this._runningLoop = false;
  2693. };
  2694. Engine.prototype._renderLoop = function () {
  2695. var _this = this;
  2696. var shouldRender = true;
  2697. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2698. shouldRender = false;
  2699. }
  2700. if (shouldRender) {
  2701. this.beginFrame();
  2702. if (this._renderFunction) {
  2703. this._renderFunction();
  2704. }
  2705. this.endFrame();
  2706. }
  2707. if (this._runningLoop) {
  2708. BABYLON.Tools.QueueNewFrame(function () {
  2709. _this._renderLoop();
  2710. });
  2711. }
  2712. };
  2713. Engine.prototype.runRenderLoop = function (renderFunction) {
  2714. var _this = this;
  2715. this._runningLoop = true;
  2716. this._renderFunction = renderFunction;
  2717. BABYLON.Tools.QueueNewFrame(function () {
  2718. _this._renderLoop();
  2719. });
  2720. };
  2721. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2722. if (this.isFullscreen) {
  2723. BABYLON.Tools.ExitFullscreen();
  2724. } else {
  2725. this._pointerLockRequested = requestPointerLock;
  2726. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2727. }
  2728. };
  2729. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2730. this.applyStates();
  2731. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2732. if (this._depthCullingState.depthMask) {
  2733. this._gl.clearDepth(1.0);
  2734. }
  2735. var mode = 0;
  2736. if (backBuffer)
  2737. mode |= this._gl.COLOR_BUFFER_BIT;
  2738. if (depthStencil && this._depthCullingState.depthMask)
  2739. mode |= this._gl.DEPTH_BUFFER_BIT;
  2740. this._gl.clear(mode);
  2741. };
  2742. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2743. var width = requiredWidth || this._renderingCanvas.width;
  2744. var height = requiredHeight || this._renderingCanvas.height;
  2745. var x = viewport.x || 0;
  2746. var y = viewport.y || 0;
  2747. this._cachedViewport = viewport;
  2748. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2749. };
  2750. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2751. this._cachedViewport = null;
  2752. this._gl.viewport(x, y, width, height);
  2753. };
  2754. Engine.prototype.beginFrame = function () {
  2755. BABYLON.Tools._MeasureFps();
  2756. };
  2757. Engine.prototype.endFrame = function () {
  2758. this.flushFramebuffer();
  2759. };
  2760. Engine.prototype.resize = function () {
  2761. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2762. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2763. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2764. };
  2765. Engine.prototype.bindFramebuffer = function (texture) {
  2766. this._currentRenderTarget = texture;
  2767. var gl = this._gl;
  2768. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2769. this._gl.viewport(0, 0, texture._width, texture._height);
  2770. this.wipeCaches();
  2771. };
  2772. Engine.prototype.unBindFramebuffer = function (texture) {
  2773. this._currentRenderTarget = null;
  2774. if (texture.generateMipMaps) {
  2775. var gl = this._gl;
  2776. gl.bindTexture(gl.TEXTURE_2D, texture);
  2777. gl.generateMipmap(gl.TEXTURE_2D);
  2778. gl.bindTexture(gl.TEXTURE_2D, null);
  2779. }
  2780. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2781. };
  2782. Engine.prototype.flushFramebuffer = function () {
  2783. this._gl.flush();
  2784. };
  2785. Engine.prototype.restoreDefaultFramebuffer = function () {
  2786. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2787. this.setViewport(this._cachedViewport);
  2788. this.wipeCaches();
  2789. };
  2790. Engine.prototype._resetVertexBufferBinding = function () {
  2791. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2792. this._cachedVertexBuffers = null;
  2793. };
  2794. Engine.prototype.createVertexBuffer = function (vertices) {
  2795. var vbo = this._gl.createBuffer();
  2796. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2797. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2798. this._resetVertexBufferBinding();
  2799. vbo.references = 1;
  2800. return vbo;
  2801. };
  2802. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2803. var vbo = this._gl.createBuffer();
  2804. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2805. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2806. this._resetVertexBufferBinding();
  2807. vbo.references = 1;
  2808. return vbo;
  2809. };
  2810. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2811. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2812. if (vertices instanceof Float32Array) {
  2813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2814. } else {
  2815. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2816. }
  2817. this._resetVertexBufferBinding();
  2818. };
  2819. Engine.prototype._resetIndexBufferBinding = function () {
  2820. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2821. this._cachedIndexBuffer = null;
  2822. };
  2823. Engine.prototype.createIndexBuffer = function (indices) {
  2824. var vbo = this._gl.createBuffer();
  2825. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2826. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2827. this._resetIndexBufferBinding();
  2828. vbo.references = 1;
  2829. return vbo;
  2830. };
  2831. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2832. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2833. this._cachedVertexBuffers = vertexBuffer;
  2834. this._cachedEffectForVertexBuffers = effect;
  2835. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2836. var offset = 0;
  2837. for (var index = 0; index < vertexDeclaration.length; index++) {
  2838. var order = effect.getAttributeLocation(index);
  2839. if (order >= 0) {
  2840. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2841. }
  2842. offset += vertexDeclaration[index] * 4;
  2843. }
  2844. }
  2845. if (this._cachedIndexBuffer !== indexBuffer) {
  2846. this._cachedIndexBuffer = indexBuffer;
  2847. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2848. }
  2849. };
  2850. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2851. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2852. this._cachedVertexBuffers = vertexBuffers;
  2853. this._cachedEffectForVertexBuffers = effect;
  2854. var attributes = effect.getAttributesNames();
  2855. for (var index = 0; index < attributes.length; index++) {
  2856. var order = effect.getAttributeLocation(index);
  2857. if (order >= 0) {
  2858. var vertexBuffer = vertexBuffers[attributes[index]];
  2859. if (!vertexBuffer) {
  2860. continue;
  2861. }
  2862. var stride = vertexBuffer.getStrideSize();
  2863. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2864. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2865. }
  2866. }
  2867. }
  2868. if (this._cachedIndexBuffer !== indexBuffer) {
  2869. this._cachedIndexBuffer = indexBuffer;
  2870. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2871. }
  2872. };
  2873. Engine.prototype._releaseBuffer = function (buffer) {
  2874. buffer.references--;
  2875. if (buffer.references === 0) {
  2876. this._gl.deleteBuffer(buffer);
  2877. return true;
  2878. }
  2879. return false;
  2880. };
  2881. Engine.prototype.createInstancesBuffer = function (capacity) {
  2882. var buffer = this._gl.createBuffer();
  2883. buffer.capacity = capacity;
  2884. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2885. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2886. return buffer;
  2887. };
  2888. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2889. this._gl.deleteBuffer(buffer);
  2890. };
  2891. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2893. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2894. for (var index = 0; index < 4; index++) {
  2895. var offsetLocation = offsetLocations[index];
  2896. this._gl.enableVertexAttribArray(offsetLocation);
  2897. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2898. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2899. }
  2900. };
  2901. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2903. for (var index = 0; index < 4; index++) {
  2904. var offsetLocation = offsetLocations[index];
  2905. this._gl.disableVertexAttribArray(offsetLocation);
  2906. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2907. }
  2908. };
  2909. Engine.prototype.applyStates = function () {
  2910. this._depthCullingState.apply(this._gl);
  2911. this._alphaState.apply(this._gl);
  2912. };
  2913. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2914. this.applyStates();
  2915. if (instancesCount) {
  2916. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2917. return;
  2918. }
  2919. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2920. };
  2921. Engine.prototype._releaseEffect = function (effect) {
  2922. if (this._compiledEffects[effect._key]) {
  2923. delete this._compiledEffects[effect._key];
  2924. if (effect.getProgram()) {
  2925. this._gl.deleteProgram(effect.getProgram());
  2926. }
  2927. }
  2928. };
  2929. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2930. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2931. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2932. var name = vertex + "+" + fragment + "@" + defines;
  2933. if (this._compiledEffects[name]) {
  2934. return this._compiledEffects[name];
  2935. }
  2936. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2937. effect._key = name;
  2938. this._compiledEffects[name] = effect;
  2939. return effect;
  2940. };
  2941. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2942. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2943. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2944. var shaderProgram = this._gl.createProgram();
  2945. this._gl.attachShader(shaderProgram, vertexShader);
  2946. this._gl.attachShader(shaderProgram, fragmentShader);
  2947. this._gl.linkProgram(shaderProgram);
  2948. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2949. if (!linked) {
  2950. var error = this._gl.getProgramInfoLog(shaderProgram);
  2951. if (error) {
  2952. throw new Error(error);
  2953. }
  2954. }
  2955. this._gl.deleteShader(vertexShader);
  2956. this._gl.deleteShader(fragmentShader);
  2957. return shaderProgram;
  2958. };
  2959. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2960. var results = [];
  2961. for (var index = 0; index < uniformsNames.length; index++) {
  2962. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2963. }
  2964. return results;
  2965. };
  2966. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2967. var results = [];
  2968. for (var index = 0; index < attributesNames.length; index++) {
  2969. try {
  2970. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2971. } catch (e) {
  2972. results.push(-1);
  2973. }
  2974. }
  2975. return results;
  2976. };
  2977. Engine.prototype.enableEffect = function (effect) {
  2978. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  2979. return;
  2980. }
  2981. this._vertexAttribArrays = this._vertexAttribArrays || [];
  2982. this._gl.useProgram(effect.getProgram());
  2983. for (var i in this._vertexAttribArrays) {
  2984. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  2985. continue;
  2986. }
  2987. this._vertexAttribArrays[i] = false;
  2988. this._gl.disableVertexAttribArray(i);
  2989. }
  2990. var attributesCount = effect.getAttributesCount();
  2991. for (var index = 0; index < attributesCount; index++) {
  2992. var order = effect.getAttributeLocation(index);
  2993. if (order >= 0) {
  2994. this._vertexAttribArrays[order] = true;
  2995. this._gl.enableVertexAttribArray(order);
  2996. }
  2997. }
  2998. this._currentEffect = effect;
  2999. };
  3000. Engine.prototype.setArray = function (uniform, array) {
  3001. if (!uniform)
  3002. return;
  3003. this._gl.uniform1fv(uniform, array);
  3004. };
  3005. Engine.prototype.setMatrices = function (uniform, matrices) {
  3006. if (!uniform)
  3007. return;
  3008. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3009. };
  3010. Engine.prototype.setMatrix = function (uniform, matrix) {
  3011. if (!uniform)
  3012. return;
  3013. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3014. };
  3015. Engine.prototype.setFloat = function (uniform, value) {
  3016. if (!uniform)
  3017. return;
  3018. this._gl.uniform1f(uniform, value);
  3019. };
  3020. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3021. if (!uniform)
  3022. return;
  3023. this._gl.uniform2f(uniform, x, y);
  3024. };
  3025. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3026. if (!uniform)
  3027. return;
  3028. this._gl.uniform3f(uniform, x, y, z);
  3029. };
  3030. Engine.prototype.setBool = function (uniform, bool) {
  3031. if (!uniform)
  3032. return;
  3033. this._gl.uniform1i(uniform, bool);
  3034. };
  3035. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3036. if (!uniform)
  3037. return;
  3038. this._gl.uniform4f(uniform, x, y, z, w);
  3039. };
  3040. Engine.prototype.setColor3 = function (uniform, color3) {
  3041. if (!uniform)
  3042. return;
  3043. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3044. };
  3045. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3046. if (!uniform)
  3047. return;
  3048. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3049. };
  3050. Engine.prototype.setState = function (culling, force) {
  3051. if (this._depthCullingState.cull !== culling || force) {
  3052. if (culling) {
  3053. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3054. this._depthCullingState.cull = true;
  3055. } else {
  3056. this._depthCullingState.cull = false;
  3057. }
  3058. }
  3059. };
  3060. Engine.prototype.setDepthBuffer = function (enable) {
  3061. this._depthCullingState.depthTest = enable;
  3062. };
  3063. Engine.prototype.getDepthWrite = function () {
  3064. return this._depthCullingState.depthMask;
  3065. };
  3066. Engine.prototype.setDepthWrite = function (enable) {
  3067. this._depthCullingState.depthMask = enable;
  3068. };
  3069. Engine.prototype.setColorWrite = function (enable) {
  3070. this._gl.colorMask(enable, enable, enable, enable);
  3071. };
  3072. Engine.prototype.setAlphaMode = function (mode) {
  3073. switch (mode) {
  3074. case BABYLON.Engine.ALPHA_DISABLE:
  3075. this.setDepthWrite(true);
  3076. this._alphaState.alphaBlend = false;
  3077. break;
  3078. case BABYLON.Engine.ALPHA_COMBINE:
  3079. this.setDepthWrite(false);
  3080. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3081. this._alphaState.alphaBlend = true;
  3082. break;
  3083. case BABYLON.Engine.ALPHA_ADD:
  3084. this.setDepthWrite(false);
  3085. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3086. this._alphaState.alphaBlend = true;
  3087. break;
  3088. }
  3089. };
  3090. Engine.prototype.setAlphaTesting = function (enable) {
  3091. this._alphaTest = enable;
  3092. };
  3093. Engine.prototype.getAlphaTesting = function () {
  3094. return this._alphaTest;
  3095. };
  3096. Engine.prototype.wipeCaches = function () {
  3097. this._activeTexturesCache = [];
  3098. this._currentEffect = null;
  3099. this._depthCullingState.reset();
  3100. this._alphaState.reset();
  3101. this._cachedVertexBuffers = null;
  3102. this._cachedIndexBuffer = null;
  3103. this._cachedEffectForVertexBuffers = null;
  3104. };
  3105. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3106. var gl = this._gl;
  3107. gl.bindTexture(gl.TEXTURE_2D, texture);
  3108. var magFilter = gl.NEAREST;
  3109. var minFilter = gl.NEAREST;
  3110. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3111. magFilter = gl.LINEAR;
  3112. minFilter = gl.LINEAR;
  3113. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3114. magFilter = gl.LINEAR;
  3115. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3116. }
  3117. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3118. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3119. gl.bindTexture(gl.TEXTURE_2D, null);
  3120. };
  3121. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3122. var _this = this;
  3123. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3124. var texture = this._gl.createTexture();
  3125. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3126. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3127. var isTGA = (extension === ".tga");
  3128. scene._addPendingData(texture);
  3129. texture.url = url;
  3130. texture.noMipmap = noMipmap;
  3131. texture.references = 1;
  3132. this._loadedTexturesCache.push(texture);
  3133. if (isTGA) {
  3134. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3135. var data = new Uint8Array(arrayBuffer);
  3136. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3137. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3138. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3139. }, samplingMode);
  3140. }, null, scene.database, true);
  3141. } else if (isDDS) {
  3142. BABYLON.Tools.LoadFile(url, function (data) {
  3143. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3144. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3145. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3146. console.log("loading " + url);
  3147. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3148. }, samplingMode);
  3149. }, null, scene.database, true);
  3150. } else {
  3151. var onload = function (img) {
  3152. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3153. var isPot = (img.width == potWidth && img.height == potHeight);
  3154. if (!isPot) {
  3155. _this._workingCanvas.width = potWidth;
  3156. _this._workingCanvas.height = potHeight;
  3157. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3158. }
  3159. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3160. }, samplingMode);
  3161. };
  3162. var onerror = function () {
  3163. scene._removePendingData(texture);
  3164. };
  3165. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3166. }
  3167. return texture;
  3168. };
  3169. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3170. var texture = this._gl.createTexture();
  3171. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3172. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3173. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3174. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3175. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3176. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3177. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3178. this._activeTexturesCache = [];
  3179. texture._baseWidth = width;
  3180. texture._baseHeight = height;
  3181. texture._width = width;
  3182. texture._height = height;
  3183. texture.isReady = false;
  3184. texture.generateMipMaps = generateMipMaps;
  3185. texture.references = 1;
  3186. this._loadedTexturesCache.push(texture);
  3187. return texture;
  3188. };
  3189. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3190. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3191. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3192. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3193. if (texture.generateMipMaps) {
  3194. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3195. }
  3196. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3197. this._activeTexturesCache = [];
  3198. texture.isReady = true;
  3199. };
  3200. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3201. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3202. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3203. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3204. if (!texture._workingCanvas) {
  3205. texture._workingCanvas = document.createElement("canvas");
  3206. texture._workingContext = texture._workingCanvas.getContext("2d");
  3207. texture._workingCanvas.width = texture._width;
  3208. texture._workingCanvas.height = texture._height;
  3209. }
  3210. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3211. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3212. } else {
  3213. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3214. }
  3215. if (texture.generateMipMaps) {
  3216. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3217. }
  3218. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3219. this._activeTexturesCache = [];
  3220. texture.isReady = true;
  3221. };
  3222. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3223. var generateMipMaps = false;
  3224. var generateDepthBuffer = true;
  3225. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3226. if (options !== undefined) {
  3227. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3228. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3229. if (options.samplingMode !== undefined) {
  3230. samplingMode = options.samplingMode;
  3231. }
  3232. }
  3233. var gl = this._gl;
  3234. var texture = gl.createTexture();
  3235. gl.bindTexture(gl.TEXTURE_2D, texture);
  3236. var width = size.width || size;
  3237. var height = size.height || size;
  3238. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3243. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3244. var depthBuffer;
  3245. if (generateDepthBuffer) {
  3246. depthBuffer = gl.createRenderbuffer();
  3247. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3248. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3249. }
  3250. var framebuffer = gl.createFramebuffer();
  3251. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3252. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3253. if (generateDepthBuffer) {
  3254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3255. }
  3256. gl.bindTexture(gl.TEXTURE_2D, null);
  3257. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3258. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3259. texture._framebuffer = framebuffer;
  3260. if (generateDepthBuffer) {
  3261. texture._depthBuffer = depthBuffer;
  3262. }
  3263. texture._width = width;
  3264. texture._height = height;
  3265. texture.isReady = true;
  3266. texture.generateMipMaps = generateMipMaps;
  3267. texture.references = 1;
  3268. this._activeTexturesCache = [];
  3269. this._loadedTexturesCache.push(texture);
  3270. return texture;
  3271. };
  3272. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3273. var _this = this;
  3274. var gl = this._gl;
  3275. var texture = gl.createTexture();
  3276. texture.isCube = true;
  3277. texture.url = rootUrl;
  3278. texture.references = 1;
  3279. this._loadedTexturesCache.push(texture);
  3280. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3281. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3282. if (isDDS) {
  3283. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3284. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3285. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3286. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3287. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3288. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3289. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3290. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3291. }
  3292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3296. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3297. _this._activeTexturesCache = [];
  3298. texture._width = info.width;
  3299. texture._height = info.height;
  3300. texture.isReady = true;
  3301. }, null, null, true);
  3302. } else {
  3303. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3304. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3305. var height = width;
  3306. _this._workingCanvas.width = width;
  3307. _this._workingCanvas.height = height;
  3308. var faces = [
  3309. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3310. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3311. ];
  3312. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3313. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3314. for (var index = 0; index < faces.length; index++) {
  3315. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3316. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3317. }
  3318. if (!noMipmap) {
  3319. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3320. }
  3321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3324. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3325. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3326. _this._activeTexturesCache = [];
  3327. texture._width = width;
  3328. texture._height = height;
  3329. texture.isReady = true;
  3330. }, extensions);
  3331. }
  3332. return texture;
  3333. };
  3334. Engine.prototype._releaseTexture = function (texture) {
  3335. var gl = this._gl;
  3336. if (texture._framebuffer) {
  3337. gl.deleteFramebuffer(texture._framebuffer);
  3338. }
  3339. if (texture._depthBuffer) {
  3340. gl.deleteRenderbuffer(texture._depthBuffer);
  3341. }
  3342. gl.deleteTexture(texture);
  3343. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3344. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3345. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3346. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3347. this._activeTexturesCache[channel] = null;
  3348. }
  3349. var index = this._loadedTexturesCache.indexOf(texture);
  3350. if (index !== -1) {
  3351. this._loadedTexturesCache.splice(index, 1);
  3352. }
  3353. };
  3354. Engine.prototype.bindSamplers = function (effect) {
  3355. this._gl.useProgram(effect.getProgram());
  3356. var samplers = effect.getSamplers();
  3357. for (var index = 0; index < samplers.length; index++) {
  3358. var uniform = effect.getUniform(samplers[index]);
  3359. this._gl.uniform1i(uniform, index);
  3360. }
  3361. this._currentEffect = null;
  3362. };
  3363. Engine.prototype._bindTexture = function (channel, texture) {
  3364. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3365. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3366. this._activeTexturesCache[channel] = null;
  3367. };
  3368. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3369. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3370. };
  3371. Engine.prototype.setTexture = function (channel, texture) {
  3372. if (channel < 0) {
  3373. return;
  3374. }
  3375. if (!texture || !texture.isReady()) {
  3376. if (this._activeTexturesCache[channel] != null) {
  3377. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3378. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3379. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3380. this._activeTexturesCache[channel] = null;
  3381. }
  3382. return;
  3383. }
  3384. if (texture instanceof BABYLON.VideoTexture) {
  3385. if (texture.update()) {
  3386. this._activeTexturesCache[channel] = null;
  3387. }
  3388. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3389. texture.delayLoad();
  3390. return;
  3391. }
  3392. if (this._activeTexturesCache[channel] == texture) {
  3393. return;
  3394. }
  3395. this._activeTexturesCache[channel] = texture;
  3396. var internalTexture = texture.getInternalTexture();
  3397. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3398. if (internalTexture.isCube) {
  3399. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3400. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3401. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3402. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3403. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3404. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3405. }
  3406. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3407. } else {
  3408. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3409. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3410. internalTexture._cachedWrapU = texture.wrapU;
  3411. switch (texture.wrapU) {
  3412. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3413. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3414. break;
  3415. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3416. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3417. break;
  3418. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3420. break;
  3421. }
  3422. }
  3423. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3424. internalTexture._cachedWrapV = texture.wrapV;
  3425. switch (texture.wrapV) {
  3426. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3427. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3428. break;
  3429. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3430. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3431. break;
  3432. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3433. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3434. break;
  3435. }
  3436. }
  3437. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3438. }
  3439. };
  3440. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3441. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3442. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3443. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3444. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3445. }
  3446. };
  3447. Engine.prototype.readPixels = function (x, y, width, height) {
  3448. var data = new Uint8Array(height * width * 4);
  3449. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3450. return data;
  3451. };
  3452. Engine.prototype.dispose = function () {
  3453. this.hideLoadingUI();
  3454. this.stopRenderLoop();
  3455. while (this.scenes.length) {
  3456. this.scenes[0].dispose();
  3457. }
  3458. for (var name in this._compiledEffects) {
  3459. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3460. }
  3461. for (var i in this._vertexAttribArrays) {
  3462. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3463. continue;
  3464. }
  3465. this._gl.disableVertexAttribArray(i);
  3466. }
  3467. window.removeEventListener("blur", this._onBlur);
  3468. window.removeEventListener("focus", this._onFocus);
  3469. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3470. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3471. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3472. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3473. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3474. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3475. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3476. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3477. };
  3478. Engine.prototype.displayLoadingUI = function () {
  3479. var _this = this;
  3480. this._loadingDiv = document.createElement("div");
  3481. this._loadingDiv.style.opacity = "0";
  3482. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3483. this._loadingTextDiv = document.createElement("div");
  3484. this._loadingTextDiv.style.position = "absolute";
  3485. this._loadingTextDiv.style.left = "0";
  3486. this._loadingTextDiv.style.top = "50%";
  3487. this._loadingTextDiv.style.marginTop = "80px";
  3488. this._loadingTextDiv.style.width = "100%";
  3489. this._loadingTextDiv.style.height = "20px";
  3490. this._loadingTextDiv.style.fontFamily = "Arial";
  3491. this._loadingTextDiv.style.fontSize = "14px";
  3492. this._loadingTextDiv.style.color = "white";
  3493. this._loadingTextDiv.style.textAlign = "center";
  3494. this._loadingTextDiv.innerHTML = "Loading";
  3495. this._loadingDiv.appendChild(this._loadingTextDiv);
  3496. var imgBack = new Image();
  3497. 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==";
  3498. imgBack.style.position = "absolute";
  3499. imgBack.style.left = "50%";
  3500. imgBack.style.top = "50%";
  3501. imgBack.style.marginLeft = "-50px";
  3502. imgBack.style.marginTop = "-50px";
  3503. imgBack.style.transition = "transform 1.0s ease";
  3504. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3505. var deg = 360;
  3506. var onTransitionEnd = function () {
  3507. deg += 360;
  3508. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3509. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3510. };
  3511. imgBack.addEventListener("transitionend", onTransitionEnd);
  3512. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3513. this._loadingDiv.appendChild(imgBack);
  3514. var imgFront = new Image();
  3515. 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=";
  3516. imgFront.style.position = "absolute";
  3517. imgFront.style.left = "50%";
  3518. imgFront.style.top = "50%";
  3519. imgFront.style.marginLeft = "-50px";
  3520. imgFront.style.marginTop = "-50px";
  3521. this._loadingDiv.appendChild(imgFront);
  3522. this._resizeLoadingUI = function () {
  3523. var canvasRect = _this.getRenderingCanvasClientRect();
  3524. _this._loadingDiv.style.position = "absolute";
  3525. _this._loadingDiv.style.left = canvasRect.left + "px";
  3526. _this._loadingDiv.style.top = canvasRect.top + "px";
  3527. _this._loadingDiv.style.width = canvasRect.width + "px";
  3528. _this._loadingDiv.style.height = canvasRect.height + "px";
  3529. };
  3530. this._resizeLoadingUI();
  3531. window.addEventListener("resize", this._resizeLoadingUI);
  3532. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3533. document.body.appendChild(this._loadingDiv);
  3534. setTimeout(function () {
  3535. _this._loadingDiv.style.opacity = "1";
  3536. imgBack.style.transform = "rotateZ(360deg)";
  3537. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3538. }, 0);
  3539. };
  3540. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3541. set: function (text) {
  3542. if (!this._loadingDiv) {
  3543. return;
  3544. }
  3545. this._loadingTextDiv.innerHTML = text;
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3551. get: function () {
  3552. return this._loadingDivBackgroundColor;
  3553. },
  3554. set: function (color) {
  3555. this._loadingDivBackgroundColor = color;
  3556. if (!this._loadingDiv) {
  3557. return;
  3558. }
  3559. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Engine.prototype.hideLoadingUI = function () {
  3565. var _this = this;
  3566. if (!this._loadingDiv) {
  3567. return;
  3568. }
  3569. var onTransitionEnd = function () {
  3570. if (!_this._loadingDiv) {
  3571. return;
  3572. }
  3573. document.body.removeChild(_this._loadingDiv);
  3574. window.removeEventListener("resize", _this._resizeLoadingUI);
  3575. _this._loadingDiv = null;
  3576. };
  3577. this._loadingDiv.style.opacity = "0";
  3578. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3579. };
  3580. Engine.isSupported = function () {
  3581. try {
  3582. var tempcanvas = document.createElement("canvas");
  3583. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3584. return gl != null && !!window.WebGLRenderingContext;
  3585. } catch (e) {
  3586. return false;
  3587. }
  3588. };
  3589. Engine._ALPHA_DISABLE = 0;
  3590. Engine._ALPHA_ADD = 1;
  3591. Engine._ALPHA_COMBINE = 2;
  3592. Engine._DELAYLOADSTATE_NONE = 0;
  3593. Engine._DELAYLOADSTATE_LOADED = 1;
  3594. Engine._DELAYLOADSTATE_LOADING = 2;
  3595. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3596. Engine.Epsilon = 0.001;
  3597. Engine.CollisionsEpsilon = 0.001;
  3598. Engine.ShadersRepository = "Babylon/Shaders/";
  3599. return Engine;
  3600. })();
  3601. BABYLON.Engine = Engine;
  3602. })(BABYLON || (BABYLON = {}));
  3603. var BABYLON;
  3604. (function (BABYLON) {
  3605. var Node = (function () {
  3606. function Node(name, scene) {
  3607. this.state = "";
  3608. this.animations = new Array();
  3609. this._childrenFlag = -1;
  3610. this._isEnabled = true;
  3611. this._isReady = true;
  3612. this._currentRenderId = -1;
  3613. this.name = name;
  3614. this.id = name;
  3615. this._scene = scene;
  3616. this._initCache();
  3617. }
  3618. Node.prototype.getScene = function () {
  3619. return this._scene;
  3620. };
  3621. Node.prototype.getEngine = function () {
  3622. return this._scene.getEngine();
  3623. };
  3624. Node.prototype.getWorldMatrix = function () {
  3625. return BABYLON.Matrix.Identity();
  3626. };
  3627. Node.prototype._initCache = function () {
  3628. this._cache = {};
  3629. this._cache.parent = undefined;
  3630. };
  3631. Node.prototype.updateCache = function (force) {
  3632. if (!force && this.isSynchronized())
  3633. return;
  3634. this._cache.parent = this.parent;
  3635. this._updateCache();
  3636. };
  3637. Node.prototype._updateCache = function (ignoreParentClass) {
  3638. };
  3639. Node.prototype._isSynchronized = function () {
  3640. return true;
  3641. };
  3642. Node.prototype.isSynchronizedWithParent = function () {
  3643. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3644. };
  3645. Node.prototype.isSynchronized = function (updateCache) {
  3646. var check = this.hasNewParent();
  3647. check = check || !this.isSynchronizedWithParent();
  3648. check = check || !this._isSynchronized();
  3649. if (updateCache)
  3650. this.updateCache(true);
  3651. return !check;
  3652. };
  3653. Node.prototype.hasNewParent = function (update) {
  3654. if (this._cache.parent === this.parent)
  3655. return false;
  3656. if (update)
  3657. this._cache.parent = this.parent;
  3658. return true;
  3659. };
  3660. Node.prototype.isReady = function () {
  3661. return this._isReady;
  3662. };
  3663. Node.prototype.isEnabled = function () {
  3664. if (!this._isEnabled) {
  3665. return false;
  3666. }
  3667. if (this.parent) {
  3668. return this.parent.isEnabled();
  3669. }
  3670. return true;
  3671. };
  3672. Node.prototype.setEnabled = function (value) {
  3673. this._isEnabled = value;
  3674. };
  3675. Node.prototype.isDescendantOf = function (ancestor) {
  3676. if (this.parent) {
  3677. if (this.parent === ancestor) {
  3678. return true;
  3679. }
  3680. return this.parent.isDescendantOf(ancestor);
  3681. }
  3682. return false;
  3683. };
  3684. Node.prototype._getDescendants = function (list, results) {
  3685. for (var index = 0; index < list.length; index++) {
  3686. var item = list[index];
  3687. if (item.isDescendantOf(this)) {
  3688. results.push(item);
  3689. }
  3690. }
  3691. };
  3692. Node.prototype.getDescendants = function () {
  3693. var results = [];
  3694. this._getDescendants(this._scene.meshes, results);
  3695. this._getDescendants(this._scene.lights, results);
  3696. this._getDescendants(this._scene.cameras, results);
  3697. return results;
  3698. };
  3699. Node.prototype._setReady = function (state) {
  3700. if (state == this._isReady) {
  3701. return;
  3702. }
  3703. if (!state) {
  3704. this._isReady = false;
  3705. return;
  3706. }
  3707. this._isReady = true;
  3708. if (this.onReady) {
  3709. this.onReady(this);
  3710. }
  3711. };
  3712. return Node;
  3713. })();
  3714. BABYLON.Node = Node;
  3715. })(BABYLON || (BABYLON = {}));
  3716. var BABYLON;
  3717. (function (BABYLON) {
  3718. var BoundingSphere = (function () {
  3719. function BoundingSphere(minimum, maximum) {
  3720. this.minimum = minimum;
  3721. this.maximum = maximum;
  3722. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3723. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3724. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3725. this.radius = distance * 0.5;
  3726. this.centerWorld = BABYLON.Vector3.Zero();
  3727. this._update(BABYLON.Matrix.Identity());
  3728. }
  3729. BoundingSphere.prototype._update = function (world) {
  3730. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3731. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3732. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3733. };
  3734. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3735. for (var i = 0; i < 6; i++) {
  3736. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3737. return false;
  3738. }
  3739. return true;
  3740. };
  3741. BoundingSphere.prototype.intersectsPoint = function (point) {
  3742. var x = this.centerWorld.x - point.x;
  3743. var y = this.centerWorld.y - point.y;
  3744. var z = this.centerWorld.z - point.z;
  3745. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3746. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3747. return false;
  3748. return true;
  3749. };
  3750. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3751. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3752. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3753. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3755. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3756. return false;
  3757. return true;
  3758. };
  3759. return BoundingSphere;
  3760. })();
  3761. BABYLON.BoundingSphere = BoundingSphere;
  3762. })(BABYLON || (BABYLON = {}));
  3763. var BABYLON;
  3764. (function (BABYLON) {
  3765. var BoundingBox = (function () {
  3766. function BoundingBox(minimum, maximum) {
  3767. this.minimum = minimum;
  3768. this.maximum = maximum;
  3769. this.vectors = new Array();
  3770. this.vectorsWorld = new Array();
  3771. this.vectors.push(this.minimum.clone());
  3772. this.vectors.push(this.maximum.clone());
  3773. this.vectors.push(this.minimum.clone());
  3774. this.vectors[2].x = this.maximum.x;
  3775. this.vectors.push(this.minimum.clone());
  3776. this.vectors[3].y = this.maximum.y;
  3777. this.vectors.push(this.minimum.clone());
  3778. this.vectors[4].z = this.maximum.z;
  3779. this.vectors.push(this.maximum.clone());
  3780. this.vectors[5].z = this.minimum.z;
  3781. this.vectors.push(this.maximum.clone());
  3782. this.vectors[6].x = this.minimum.x;
  3783. this.vectors.push(this.maximum.clone());
  3784. this.vectors[7].y = this.minimum.y;
  3785. this.center = this.maximum.add(this.minimum).scale(0.5);
  3786. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3787. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3788. for (var index = 0; index < this.vectors.length; index++) {
  3789. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3790. }
  3791. this.minimumWorld = BABYLON.Vector3.Zero();
  3792. this.maximumWorld = BABYLON.Vector3.Zero();
  3793. this._update(BABYLON.Matrix.Identity());
  3794. }
  3795. BoundingBox.prototype.getWorldMatrix = function () {
  3796. return this._worldMatrix;
  3797. };
  3798. BoundingBox.prototype._update = function (world) {
  3799. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3800. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3801. for (var index = 0; index < this.vectors.length; index++) {
  3802. var v = this.vectorsWorld[index];
  3803. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3804. if (v.x < this.minimumWorld.x)
  3805. this.minimumWorld.x = v.x;
  3806. if (v.y < this.minimumWorld.y)
  3807. this.minimumWorld.y = v.y;
  3808. if (v.z < this.minimumWorld.z)
  3809. this.minimumWorld.z = v.z;
  3810. if (v.x > this.maximumWorld.x)
  3811. this.maximumWorld.x = v.x;
  3812. if (v.y > this.maximumWorld.y)
  3813. this.maximumWorld.y = v.y;
  3814. if (v.z > this.maximumWorld.z)
  3815. this.maximumWorld.z = v.z;
  3816. }
  3817. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3818. this.center.scaleInPlace(0.5);
  3819. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3820. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3821. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3822. this._worldMatrix = world;
  3823. };
  3824. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3825. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3826. };
  3827. BoundingBox.prototype.intersectsPoint = function (point) {
  3828. var delta = BABYLON.Engine.Epsilon;
  3829. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3830. return false;
  3831. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3832. return false;
  3833. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3834. return false;
  3835. return true;
  3836. };
  3837. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3838. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3839. };
  3840. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3841. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3842. return false;
  3843. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3844. return false;
  3845. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3846. return false;
  3847. return true;
  3848. };
  3849. BoundingBox.Intersects = function (box0, box1) {
  3850. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3851. return false;
  3852. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3853. return false;
  3854. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3855. return false;
  3856. return true;
  3857. };
  3858. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3859. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3860. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3861. return (num <= (sphereRadius * sphereRadius));
  3862. };
  3863. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3864. for (var p = 0; p < 6; p++) {
  3865. var inCount = 8;
  3866. for (var i = 0; i < 8; i++) {
  3867. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3868. --inCount;
  3869. } else {
  3870. break;
  3871. }
  3872. }
  3873. if (inCount == 0)
  3874. return false;
  3875. }
  3876. return true;
  3877. };
  3878. return BoundingBox;
  3879. })();
  3880. BABYLON.BoundingBox = BoundingBox;
  3881. })(BABYLON || (BABYLON = {}));
  3882. var BABYLON;
  3883. (function (BABYLON) {
  3884. var computeBoxExtents = function (axis, box) {
  3885. var p = BABYLON.Vector3.Dot(box.center, axis);
  3886. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3887. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3888. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3889. var r = r0 + r1 + r2;
  3890. return {
  3891. min: p - r,
  3892. max: p + r
  3893. };
  3894. };
  3895. var extentsOverlap = function (min0, max0, min1, max1) {
  3896. return !(min0 > max1 || min1 > max0);
  3897. };
  3898. var axisOverlap = function (axis, box0, box1) {
  3899. var result0 = computeBoxExtents(axis, box0);
  3900. var result1 = computeBoxExtents(axis, box1);
  3901. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3902. };
  3903. var BoundingInfo = (function () {
  3904. function BoundingInfo(minimum, maximum) {
  3905. this.minimum = minimum;
  3906. this.maximum = maximum;
  3907. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3908. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3909. }
  3910. BoundingInfo.prototype._update = function (world) {
  3911. this.boundingBox._update(world);
  3912. this.boundingSphere._update(world);
  3913. };
  3914. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3915. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3916. return false;
  3917. return this.boundingBox.isInFrustum(frustumPlanes);
  3918. };
  3919. BoundingInfo.prototype._checkCollision = function (collider) {
  3920. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3921. };
  3922. BoundingInfo.prototype.intersectsPoint = function (point) {
  3923. if (!this.boundingSphere.centerWorld) {
  3924. return false;
  3925. }
  3926. if (!this.boundingSphere.intersectsPoint(point)) {
  3927. return false;
  3928. }
  3929. if (!this.boundingBox.intersectsPoint(point)) {
  3930. return false;
  3931. }
  3932. return true;
  3933. };
  3934. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3935. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3936. return false;
  3937. }
  3938. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3939. return false;
  3940. }
  3941. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3942. return false;
  3943. }
  3944. if (!precise) {
  3945. return true;
  3946. }
  3947. var box0 = this.boundingBox;
  3948. var box1 = boundingInfo.boundingBox;
  3949. if (!axisOverlap(box0.directions[0], box0, box1))
  3950. return false;
  3951. if (!axisOverlap(box0.directions[1], box0, box1))
  3952. return false;
  3953. if (!axisOverlap(box0.directions[2], box0, box1))
  3954. return false;
  3955. if (!axisOverlap(box1.directions[0], box0, box1))
  3956. return false;
  3957. if (!axisOverlap(box1.directions[1], box0, box1))
  3958. return false;
  3959. if (!axisOverlap(box1.directions[2], box0, box1))
  3960. return false;
  3961. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3962. return false;
  3963. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3964. return false;
  3965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3966. return false;
  3967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3968. return false;
  3969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3970. return false;
  3971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3972. return false;
  3973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3974. return false;
  3975. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  3976. return false;
  3977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  3978. return false;
  3979. return true;
  3980. };
  3981. return BoundingInfo;
  3982. })();
  3983. BABYLON.BoundingInfo = BoundingInfo;
  3984. })(BABYLON || (BABYLON = {}));
  3985. var __extends = this.__extends || function (d, b) {
  3986. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3987. function __() { this.constructor = d; }
  3988. __.prototype = b.prototype;
  3989. d.prototype = new __();
  3990. };
  3991. var BABYLON;
  3992. (function (BABYLON) {
  3993. var Light = (function (_super) {
  3994. __extends(Light, _super);
  3995. function Light(name, scene) {
  3996. _super.call(this, name, scene);
  3997. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  3998. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  3999. this.intensity = 1.0;
  4000. this.range = Number.MAX_VALUE;
  4001. this.includedOnlyMeshes = new Array();
  4002. this.excludedMeshes = new Array();
  4003. this._excludedMeshesIds = new Array();
  4004. this._includedOnlyMeshesIds = new Array();
  4005. scene.lights.push(this);
  4006. }
  4007. Light.prototype.getShadowGenerator = function () {
  4008. return this._shadowGenerator;
  4009. };
  4010. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4011. };
  4012. Light.prototype._getWorldMatrix = function () {
  4013. return BABYLON.Matrix.Identity();
  4014. };
  4015. Light.prototype.canAffectMesh = function (mesh) {
  4016. if (!mesh) {
  4017. return true;
  4018. }
  4019. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4020. return false;
  4021. }
  4022. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4023. return false;
  4024. }
  4025. return true;
  4026. };
  4027. Light.prototype.getWorldMatrix = function () {
  4028. this._currentRenderId = this.getScene().getRenderId();
  4029. var worldMatrix = this._getWorldMatrix();
  4030. if (this.parent && this.parent.getWorldMatrix) {
  4031. if (!this._parentedWorldMatrix) {
  4032. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4033. }
  4034. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4035. return this._parentedWorldMatrix;
  4036. }
  4037. return worldMatrix;
  4038. };
  4039. Light.prototype.dispose = function () {
  4040. if (this._shadowGenerator) {
  4041. this._shadowGenerator.dispose();
  4042. this._shadowGenerator = null;
  4043. }
  4044. var index = this.getScene().lights.indexOf(this);
  4045. this.getScene().lights.splice(index, 1);
  4046. };
  4047. return Light;
  4048. })(BABYLON.Node);
  4049. BABYLON.Light = Light;
  4050. })(BABYLON || (BABYLON = {}));
  4051. var __extends = this.__extends || function (d, b) {
  4052. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4053. function __() { this.constructor = d; }
  4054. __.prototype = b.prototype;
  4055. d.prototype = new __();
  4056. };
  4057. var BABYLON;
  4058. (function (BABYLON) {
  4059. var PointLight = (function (_super) {
  4060. __extends(PointLight, _super);
  4061. function PointLight(name, position, scene) {
  4062. _super.call(this, name, scene);
  4063. this.position = position;
  4064. }
  4065. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4066. if (this.parent && this.parent.getWorldMatrix) {
  4067. if (!this._transformedPosition) {
  4068. this._transformedPosition = BABYLON.Vector3.Zero();
  4069. }
  4070. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4071. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4072. return;
  4073. }
  4074. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4075. };
  4076. PointLight.prototype.getShadowGenerator = function () {
  4077. return null;
  4078. };
  4079. PointLight.prototype._getWorldMatrix = function () {
  4080. if (!this._worldMatrix) {
  4081. this._worldMatrix = BABYLON.Matrix.Identity();
  4082. }
  4083. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4084. return this._worldMatrix;
  4085. };
  4086. return PointLight;
  4087. })(BABYLON.Light);
  4088. BABYLON.PointLight = PointLight;
  4089. })(BABYLON || (BABYLON = {}));
  4090. var __extends = this.__extends || function (d, b) {
  4091. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4092. function __() { this.constructor = d; }
  4093. __.prototype = b.prototype;
  4094. d.prototype = new __();
  4095. };
  4096. var BABYLON;
  4097. (function (BABYLON) {
  4098. var SpotLight = (function (_super) {
  4099. __extends(SpotLight, _super);
  4100. function SpotLight(name, position, direction, angle, exponent, scene) {
  4101. _super.call(this, name, scene);
  4102. this.position = position;
  4103. this.direction = direction;
  4104. this.angle = angle;
  4105. this.exponent = exponent;
  4106. }
  4107. SpotLight.prototype.setDirectionToTarget = function (target) {
  4108. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4109. return this.direction;
  4110. };
  4111. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4112. var normalizeDirection;
  4113. if (this.parent && this.parent.getWorldMatrix) {
  4114. if (!this._transformedDirection) {
  4115. this._transformedDirection = BABYLON.Vector3.Zero();
  4116. }
  4117. if (!this._transformedPosition) {
  4118. this._transformedPosition = BABYLON.Vector3.Zero();
  4119. }
  4120. var parentWorldMatrix = this.parent.getWorldMatrix();
  4121. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4122. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4123. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4124. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4125. } else {
  4126. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4127. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4128. }
  4129. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4130. };
  4131. SpotLight.prototype._getWorldMatrix = function () {
  4132. if (!this._worldMatrix) {
  4133. this._worldMatrix = BABYLON.Matrix.Identity();
  4134. }
  4135. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4136. return this._worldMatrix;
  4137. };
  4138. return SpotLight;
  4139. })(BABYLON.Light);
  4140. BABYLON.SpotLight = SpotLight;
  4141. })(BABYLON || (BABYLON = {}));
  4142. var __extends = this.__extends || function (d, b) {
  4143. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4144. function __() { this.constructor = d; }
  4145. __.prototype = b.prototype;
  4146. d.prototype = new __();
  4147. };
  4148. var BABYLON;
  4149. (function (BABYLON) {
  4150. var DirectionalLight = (function (_super) {
  4151. __extends(DirectionalLight, _super);
  4152. function DirectionalLight(name, direction, scene) {
  4153. _super.call(this, name, scene);
  4154. this.direction = direction;
  4155. this.position = direction.scale(-1);
  4156. }
  4157. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4158. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4159. return this.direction;
  4160. };
  4161. DirectionalLight.prototype._computeTransformedPosition = function () {
  4162. if (this.parent && this.parent.getWorldMatrix) {
  4163. if (!this._transformedPosition) {
  4164. this._transformedPosition = BABYLON.Vector3.Zero();
  4165. }
  4166. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4167. return true;
  4168. }
  4169. return false;
  4170. };
  4171. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4172. if (this.parent && this.parent.getWorldMatrix) {
  4173. if (!this._transformedDirection) {
  4174. this._transformedDirection = BABYLON.Vector3.Zero();
  4175. }
  4176. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4177. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4178. return;
  4179. }
  4180. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4181. };
  4182. DirectionalLight.prototype._getWorldMatrix = function () {
  4183. if (!this._worldMatrix) {
  4184. this._worldMatrix = BABYLON.Matrix.Identity();
  4185. }
  4186. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4187. return this._worldMatrix;
  4188. };
  4189. return DirectionalLight;
  4190. })(BABYLON.Light);
  4191. BABYLON.DirectionalLight = DirectionalLight;
  4192. })(BABYLON || (BABYLON = {}));
  4193. var BABYLON;
  4194. (function (BABYLON) {
  4195. var ShadowGenerator = (function () {
  4196. function ShadowGenerator(mapSize, light) {
  4197. var _this = this;
  4198. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4199. this._darkness = 0;
  4200. this._transparencyShadow = false;
  4201. this._viewMatrix = BABYLON.Matrix.Zero();
  4202. this._projectionMatrix = BABYLON.Matrix.Zero();
  4203. this._transformMatrix = BABYLON.Matrix.Zero();
  4204. this._worldViewProjection = BABYLON.Matrix.Zero();
  4205. this._light = light;
  4206. this._scene = light.getScene();
  4207. light._shadowGenerator = this;
  4208. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4209. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4210. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4211. this._shadowMap.renderParticles = false;
  4212. var renderSubMesh = function (subMesh) {
  4213. var mesh = subMesh.getRenderingMesh();
  4214. var scene = _this._scene;
  4215. var engine = scene.getEngine();
  4216. engine.setState(subMesh.getMaterial().backFaceCulling);
  4217. var batch = mesh._getInstancesRenderList(subMesh._id);
  4218. if (batch.mustReturn) {
  4219. return;
  4220. }
  4221. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4222. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4223. engine.enableEffect(_this._effect);
  4224. mesh._bind(subMesh, _this._effect, false);
  4225. var material = subMesh.getMaterial();
  4226. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4227. if (material && material.needAlphaTesting()) {
  4228. var alphaTexture = material.getAlphaTestTexture();
  4229. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4230. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4231. }
  4232. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4233. if (useBones) {
  4234. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4235. }
  4236. if (hardwareInstancedRendering) {
  4237. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4238. } else {
  4239. if (batch.renderSelf[subMesh._id]) {
  4240. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4241. mesh._draw(subMesh, true);
  4242. }
  4243. if (batch.visibleInstances[subMesh._id]) {
  4244. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4245. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4246. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4247. mesh._draw(subMesh, true);
  4248. }
  4249. }
  4250. }
  4251. } else {
  4252. _this._shadowMap.resetRefreshCounter();
  4253. }
  4254. };
  4255. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4256. var index;
  4257. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4258. renderSubMesh(opaqueSubMeshes.data[index]);
  4259. }
  4260. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4261. renderSubMesh(alphaTestSubMeshes.data[index]);
  4262. }
  4263. if (_this._transparencyShadow) {
  4264. for (index = 0; index < transparentSubMeshes.length; index++) {
  4265. renderSubMesh(transparentSubMeshes.data[index]);
  4266. }
  4267. }
  4268. };
  4269. }
  4270. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4271. get: function () {
  4272. return ShadowGenerator._FILTER_NONE;
  4273. },
  4274. enumerable: true,
  4275. configurable: true
  4276. });
  4277. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4278. get: function () {
  4279. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4280. },
  4281. enumerable: true,
  4282. configurable: true
  4283. });
  4284. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4285. get: function () {
  4286. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4287. },
  4288. enumerable: true,
  4289. configurable: true
  4290. });
  4291. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4292. get: function () {
  4293. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4294. },
  4295. set: function (value) {
  4296. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4297. },
  4298. enumerable: true,
  4299. configurable: true
  4300. });
  4301. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4302. get: function () {
  4303. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4304. },
  4305. set: function (value) {
  4306. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4307. },
  4308. enumerable: true,
  4309. configurable: true
  4310. });
  4311. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4312. var defines = [];
  4313. if (this.useVarianceShadowMap) {
  4314. defines.push("#define VSM");
  4315. }
  4316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4317. var mesh = subMesh.getMesh();
  4318. var material = subMesh.getMaterial();
  4319. if (material && material.needAlphaTesting()) {
  4320. defines.push("#define ALPHATEST");
  4321. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4322. attribs.push(BABYLON.VertexBuffer.UVKind);
  4323. defines.push("#define UV1");
  4324. }
  4325. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4326. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4327. defines.push("#define UV2");
  4328. }
  4329. }
  4330. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4331. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4332. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4333. defines.push("#define BONES");
  4334. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4335. }
  4336. if (useInstances) {
  4337. defines.push("#define INSTANCES");
  4338. attribs.push("world0");
  4339. attribs.push("world1");
  4340. attribs.push("world2");
  4341. attribs.push("world3");
  4342. }
  4343. var join = defines.join("\n");
  4344. if (this._cachedDefines != join) {
  4345. this._cachedDefines = join;
  4346. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4347. }
  4348. return this._effect.isReady();
  4349. };
  4350. ShadowGenerator.prototype.getShadowMap = function () {
  4351. return this._shadowMap;
  4352. };
  4353. ShadowGenerator.prototype.getLight = function () {
  4354. return this._light;
  4355. };
  4356. ShadowGenerator.prototype.getTransformMatrix = function () {
  4357. var lightPosition = this._light.position;
  4358. var lightDirection = this._light.direction;
  4359. if (this._light._computeTransformedPosition()) {
  4360. lightPosition = this._light._transformedPosition;
  4361. }
  4362. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4363. this._cachedPosition = lightPosition.clone();
  4364. this._cachedDirection = lightDirection.clone();
  4365. var activeCamera = this._scene.activeCamera;
  4366. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4367. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4368. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4369. }
  4370. return this._transformMatrix;
  4371. };
  4372. ShadowGenerator.prototype.getDarkness = function () {
  4373. return this._darkness;
  4374. };
  4375. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4376. if (darkness >= 1.0)
  4377. this._darkness = 1.0;
  4378. else if (darkness <= 0.0)
  4379. this._darkness = 0.0;
  4380. else
  4381. this._darkness = darkness;
  4382. };
  4383. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4384. this._transparencyShadow = hasShadow;
  4385. };
  4386. ShadowGenerator.prototype.dispose = function () {
  4387. this._shadowMap.dispose();
  4388. };
  4389. ShadowGenerator._FILTER_NONE = 0;
  4390. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4391. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4392. return ShadowGenerator;
  4393. })();
  4394. BABYLON.ShadowGenerator = ShadowGenerator;
  4395. })(BABYLON || (BABYLON = {}));
  4396. var __extends = this.__extends || function (d, b) {
  4397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4398. function __() { this.constructor = d; }
  4399. __.prototype = b.prototype;
  4400. d.prototype = new __();
  4401. };
  4402. var BABYLON;
  4403. (function (BABYLON) {
  4404. var HemisphericLight = (function (_super) {
  4405. __extends(HemisphericLight, _super);
  4406. function HemisphericLight(name, direction, scene) {
  4407. _super.call(this, name, scene);
  4408. this.direction = direction;
  4409. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4410. }
  4411. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4412. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4413. return this.direction;
  4414. };
  4415. HemisphericLight.prototype.getShadowGenerator = function () {
  4416. return null;
  4417. };
  4418. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4419. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4420. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4421. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4422. };
  4423. HemisphericLight.prototype._getWorldMatrix = function () {
  4424. if (!this._worldMatrix) {
  4425. this._worldMatrix = BABYLON.Matrix.Identity();
  4426. }
  4427. return this._worldMatrix;
  4428. };
  4429. return HemisphericLight;
  4430. })(BABYLON.Light);
  4431. BABYLON.HemisphericLight = HemisphericLight;
  4432. })(BABYLON || (BABYLON = {}));
  4433. var BABYLON;
  4434. (function (BABYLON) {
  4435. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4436. if (boxMin.x > sphereCenter.x + sphereRadius)
  4437. return false;
  4438. if (sphereCenter.x - sphereRadius > boxMax.x)
  4439. return false;
  4440. if (boxMin.y > sphereCenter.y + sphereRadius)
  4441. return false;
  4442. if (sphereCenter.y - sphereRadius > boxMax.y)
  4443. return false;
  4444. if (boxMin.z > sphereCenter.z + sphereRadius)
  4445. return false;
  4446. if (sphereCenter.z - sphereRadius > boxMax.z)
  4447. return false;
  4448. return true;
  4449. };
  4450. var getLowestRoot = function (a, b, c, maxR) {
  4451. var determinant = b * b - 4.0 * a * c;
  4452. var result = { root: 0, found: false };
  4453. if (determinant < 0)
  4454. return result;
  4455. var sqrtD = Math.sqrt(determinant);
  4456. var r1 = (-b - sqrtD) / (2.0 * a);
  4457. var r2 = (-b + sqrtD) / (2.0 * a);
  4458. if (r1 > r2) {
  4459. var temp = r2;
  4460. r2 = r1;
  4461. r1 = temp;
  4462. }
  4463. if (r1 > 0 && r1 < maxR) {
  4464. result.root = r1;
  4465. result.found = true;
  4466. return result;
  4467. }
  4468. if (r2 > 0 && r2 < maxR) {
  4469. result.root = r2;
  4470. result.found = true;
  4471. return result;
  4472. }
  4473. return result;
  4474. };
  4475. var Collider = (function () {
  4476. function Collider() {
  4477. this.radius = new BABYLON.Vector3(1, 1, 1);
  4478. this.retry = 0;
  4479. this.basePointWorld = BABYLON.Vector3.Zero();
  4480. this.velocityWorld = BABYLON.Vector3.Zero();
  4481. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4482. this._collisionPoint = BABYLON.Vector3.Zero();
  4483. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4484. this._tempVector = BABYLON.Vector3.Zero();
  4485. this._tempVector2 = BABYLON.Vector3.Zero();
  4486. this._tempVector3 = BABYLON.Vector3.Zero();
  4487. this._tempVector4 = BABYLON.Vector3.Zero();
  4488. this._edge = BABYLON.Vector3.Zero();
  4489. this._baseToVertex = BABYLON.Vector3.Zero();
  4490. this._destinationPoint = BABYLON.Vector3.Zero();
  4491. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4492. this._displacementVector = BABYLON.Vector3.Zero();
  4493. }
  4494. Collider.prototype._initialize = function (source, dir, e) {
  4495. this.velocity = dir;
  4496. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4497. this.basePoint = source;
  4498. source.multiplyToRef(this.radius, this.basePointWorld);
  4499. dir.multiplyToRef(this.radius, this.velocityWorld);
  4500. this.velocityWorldLength = this.velocityWorld.length();
  4501. this.epsilon = e;
  4502. this.collisionFound = false;
  4503. };
  4504. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4505. pa.subtractToRef(point, this._tempVector);
  4506. pb.subtractToRef(point, this._tempVector2);
  4507. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4508. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4509. if (d < 0)
  4510. return false;
  4511. pc.subtractToRef(point, this._tempVector3);
  4512. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4513. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4514. if (d < 0)
  4515. return false;
  4516. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4517. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4518. return d >= 0;
  4519. };
  4520. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4521. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4522. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4523. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4524. return false;
  4525. }
  4526. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4527. return false;
  4528. return true;
  4529. };
  4530. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4531. var t0;
  4532. var embeddedInPlane = false;
  4533. if (!subMesh._trianglePlanes) {
  4534. subMesh._trianglePlanes = [];
  4535. }
  4536. if (!subMesh._trianglePlanes[faceIndex]) {
  4537. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4538. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4539. }
  4540. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4541. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4542. return;
  4543. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4544. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4545. if (normalDotVelocity == 0) {
  4546. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4547. return;
  4548. embeddedInPlane = true;
  4549. t0 = 0;
  4550. } else {
  4551. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4552. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4553. if (t0 > t1) {
  4554. var temp = t1;
  4555. t1 = t0;
  4556. t0 = temp;
  4557. }
  4558. if (t0 > 1.0 || t1 < 0.0)
  4559. return;
  4560. if (t0 < 0)
  4561. t0 = 0;
  4562. if (t0 > 1.0)
  4563. t0 = 1.0;
  4564. }
  4565. this._collisionPoint.copyFromFloats(0, 0, 0);
  4566. var found = false;
  4567. var t = 1.0;
  4568. if (!embeddedInPlane) {
  4569. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4570. this.velocity.scaleToRef(t0, this._tempVector);
  4571. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4572. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4573. found = true;
  4574. t = t0;
  4575. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4576. }
  4577. }
  4578. if (!found) {
  4579. var velocitySquaredLength = this.velocity.lengthSquared();
  4580. var a = velocitySquaredLength;
  4581. this.basePoint.subtractToRef(p1, this._tempVector);
  4582. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4583. var c = this._tempVector.lengthSquared() - 1.0;
  4584. var lowestRoot = getLowestRoot(a, b, c, t);
  4585. if (lowestRoot.found) {
  4586. t = lowestRoot.root;
  4587. found = true;
  4588. this._collisionPoint.copyFrom(p1);
  4589. }
  4590. this.basePoint.subtractToRef(p2, this._tempVector);
  4591. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4592. c = this._tempVector.lengthSquared() - 1.0;
  4593. lowestRoot = getLowestRoot(a, b, c, t);
  4594. if (lowestRoot.found) {
  4595. t = lowestRoot.root;
  4596. found = true;
  4597. this._collisionPoint.copyFrom(p2);
  4598. }
  4599. this.basePoint.subtractToRef(p3, this._tempVector);
  4600. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4601. c = this._tempVector.lengthSquared() - 1.0;
  4602. lowestRoot = getLowestRoot(a, b, c, t);
  4603. if (lowestRoot.found) {
  4604. t = lowestRoot.root;
  4605. found = true;
  4606. this._collisionPoint.copyFrom(p3);
  4607. }
  4608. p2.subtractToRef(p1, this._edge);
  4609. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4610. var edgeSquaredLength = this._edge.lengthSquared();
  4611. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4612. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4613. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4614. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4615. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4616. lowestRoot = getLowestRoot(a, b, c, t);
  4617. if (lowestRoot.found) {
  4618. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4619. if (f >= 0.0 && f <= 1.0) {
  4620. t = lowestRoot.root;
  4621. found = true;
  4622. this._edge.scaleInPlace(f);
  4623. p1.addToRef(this._edge, this._collisionPoint);
  4624. }
  4625. }
  4626. p3.subtractToRef(p2, this._edge);
  4627. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4628. edgeSquaredLength = this._edge.lengthSquared();
  4629. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4630. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4631. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4632. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4633. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4634. lowestRoot = getLowestRoot(a, b, c, t);
  4635. if (lowestRoot.found) {
  4636. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4637. if (f >= 0.0 && f <= 1.0) {
  4638. t = lowestRoot.root;
  4639. found = true;
  4640. this._edge.scaleInPlace(f);
  4641. p2.addToRef(this._edge, this._collisionPoint);
  4642. }
  4643. }
  4644. p1.subtractToRef(p3, this._edge);
  4645. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4646. edgeSquaredLength = this._edge.lengthSquared();
  4647. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4648. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4649. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4650. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4651. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4652. lowestRoot = getLowestRoot(a, b, c, t);
  4653. if (lowestRoot.found) {
  4654. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4655. if (f >= 0.0 && f <= 1.0) {
  4656. t = lowestRoot.root;
  4657. found = true;
  4658. this._edge.scaleInPlace(f);
  4659. p3.addToRef(this._edge, this._collisionPoint);
  4660. }
  4661. }
  4662. }
  4663. if (found) {
  4664. var distToCollision = t * this.velocity.length();
  4665. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4666. if (!this.intersectionPoint) {
  4667. this.intersectionPoint = this._collisionPoint.clone();
  4668. } else {
  4669. this.intersectionPoint.copyFrom(this._collisionPoint);
  4670. }
  4671. this.nearestDistance = distToCollision;
  4672. this.collisionFound = true;
  4673. this.collidedMesh = subMesh.getMesh();
  4674. }
  4675. }
  4676. };
  4677. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4678. for (var i = indexStart; i < indexEnd; i += 3) {
  4679. var p1 = pts[indices[i] - decal];
  4680. var p2 = pts[indices[i + 1] - decal];
  4681. var p3 = pts[indices[i + 2] - decal];
  4682. this._testTriangle(i, subMesh, p3, p2, p1);
  4683. }
  4684. };
  4685. Collider.prototype._getResponse = function (pos, vel) {
  4686. pos.addToRef(vel, this._destinationPoint);
  4687. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4688. this.basePoint.addToRef(vel, pos);
  4689. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4690. this._slidePlaneNormal.normalize();
  4691. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4692. pos.addInPlace(this._displacementVector);
  4693. this.intersectionPoint.addInPlace(this._displacementVector);
  4694. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4695. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4696. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4697. };
  4698. return Collider;
  4699. })();
  4700. BABYLON.Collider = Collider;
  4701. })(BABYLON || (BABYLON = {}));
  4702. var __extends = this.__extends || function (d, b) {
  4703. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4704. function __() { this.constructor = d; }
  4705. __.prototype = b.prototype;
  4706. d.prototype = new __();
  4707. };
  4708. var BABYLON;
  4709. (function (BABYLON) {
  4710. var Camera = (function (_super) {
  4711. __extends(Camera, _super);
  4712. function Camera(name, position, scene) {
  4713. _super.call(this, name, scene);
  4714. this.position = position;
  4715. this.upVector = BABYLON.Vector3.Up();
  4716. this.orthoLeft = null;
  4717. this.orthoRight = null;
  4718. this.orthoBottom = null;
  4719. this.orthoTop = null;
  4720. this.fov = 0.8;
  4721. this.minZ = 1.0;
  4722. this.maxZ = 10000.0;
  4723. this.inertia = 0.9;
  4724. this.mode = Camera.PERSPECTIVE_CAMERA;
  4725. this.isIntermediate = false;
  4726. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4727. this.subCameras = [];
  4728. this.layerMask = 0xFFFFFFFF;
  4729. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4730. this._projectionMatrix = new BABYLON.Matrix();
  4731. this._postProcesses = new Array();
  4732. this._postProcessesTakenIndices = [];
  4733. scene.cameras.push(this);
  4734. if (!scene.activeCamera) {
  4735. scene.activeCamera = this;
  4736. }
  4737. }
  4738. Camera.prototype._initCache = function () {
  4739. _super.prototype._initCache.call(this);
  4740. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4741. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4742. this._cache.mode = undefined;
  4743. this._cache.minZ = undefined;
  4744. this._cache.maxZ = undefined;
  4745. this._cache.fov = undefined;
  4746. this._cache.aspectRatio = undefined;
  4747. this._cache.orthoLeft = undefined;
  4748. this._cache.orthoRight = undefined;
  4749. this._cache.orthoBottom = undefined;
  4750. this._cache.orthoTop = undefined;
  4751. this._cache.renderWidth = undefined;
  4752. this._cache.renderHeight = undefined;
  4753. };
  4754. Camera.prototype._updateCache = function (ignoreParentClass) {
  4755. if (!ignoreParentClass) {
  4756. _super.prototype._updateCache.call(this);
  4757. }
  4758. var engine = this.getEngine();
  4759. this._cache.position.copyFrom(this.position);
  4760. this._cache.upVector.copyFrom(this.upVector);
  4761. this._cache.mode = this.mode;
  4762. this._cache.minZ = this.minZ;
  4763. this._cache.maxZ = this.maxZ;
  4764. this._cache.fov = this.fov;
  4765. this._cache.aspectRatio = engine.getAspectRatio(this);
  4766. this._cache.orthoLeft = this.orthoLeft;
  4767. this._cache.orthoRight = this.orthoRight;
  4768. this._cache.orthoBottom = this.orthoBottom;
  4769. this._cache.orthoTop = this.orthoTop;
  4770. this._cache.renderWidth = engine.getRenderWidth();
  4771. this._cache.renderHeight = engine.getRenderHeight();
  4772. };
  4773. Camera.prototype._updateFromScene = function () {
  4774. this.updateCache();
  4775. this._update();
  4776. };
  4777. Camera.prototype._isSynchronized = function () {
  4778. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4779. };
  4780. Camera.prototype._isSynchronizedViewMatrix = function () {
  4781. if (!_super.prototype._isSynchronized.call(this))
  4782. return false;
  4783. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4784. };
  4785. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4786. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4787. if (!check) {
  4788. return false;
  4789. }
  4790. var engine = this.getEngine();
  4791. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4792. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4793. } else {
  4794. 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();
  4795. }
  4796. return check;
  4797. };
  4798. Camera.prototype.attachControl = function (element) {
  4799. };
  4800. Camera.prototype.detachControl = function (element) {
  4801. };
  4802. Camera.prototype._update = function () {
  4803. };
  4804. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4805. if (typeof insertAt === "undefined") { insertAt = null; }
  4806. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4807. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4808. return 0;
  4809. }
  4810. if (insertAt == null || insertAt < 0) {
  4811. this._postProcesses.push(postProcess);
  4812. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4813. return this._postProcesses.length - 1;
  4814. }
  4815. var add = 0;
  4816. if (this._postProcesses[insertAt]) {
  4817. var start = this._postProcesses.length - 1;
  4818. for (var i = start; i >= insertAt + 1; --i) {
  4819. this._postProcesses[i + 1] = this._postProcesses[i];
  4820. }
  4821. add = 1;
  4822. }
  4823. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4824. if (this._postProcessesTakenIndices[i] < insertAt) {
  4825. continue;
  4826. }
  4827. start = this._postProcessesTakenIndices.length - 1;
  4828. for (var j = start; j >= i; --j) {
  4829. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4830. }
  4831. this._postProcessesTakenIndices[i] = insertAt;
  4832. break;
  4833. }
  4834. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4835. this._postProcessesTakenIndices.push(insertAt);
  4836. }
  4837. var result = insertAt + add;
  4838. this._postProcesses[result] = postProcess;
  4839. return result;
  4840. };
  4841. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4842. if (typeof atIndices === "undefined") { atIndices = null; }
  4843. var result = [];
  4844. if (!atIndices) {
  4845. var length = this._postProcesses.length;
  4846. for (var i = 0; i < length; i++) {
  4847. if (this._postProcesses[i] !== postProcess) {
  4848. continue;
  4849. }
  4850. delete this._postProcesses[i];
  4851. var index = this._postProcessesTakenIndices.indexOf(i);
  4852. this._postProcessesTakenIndices.splice(index, 1);
  4853. }
  4854. } else {
  4855. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4856. for (i = 0; i < atIndices.length; i++) {
  4857. var foundPostProcess = this._postProcesses[atIndices[i]];
  4858. if (foundPostProcess !== postProcess) {
  4859. result.push(i);
  4860. continue;
  4861. }
  4862. delete this._postProcesses[atIndices[i]];
  4863. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4864. this._postProcessesTakenIndices.splice(index, 1);
  4865. }
  4866. }
  4867. return result;
  4868. };
  4869. Camera.prototype.getWorldMatrix = function () {
  4870. if (!this._worldMatrix) {
  4871. this._worldMatrix = BABYLON.Matrix.Identity();
  4872. }
  4873. var viewMatrix = this.getViewMatrix();
  4874. viewMatrix.invertToRef(this._worldMatrix);
  4875. return this._worldMatrix;
  4876. };
  4877. Camera.prototype._getViewMatrix = function () {
  4878. return BABYLON.Matrix.Identity();
  4879. };
  4880. Camera.prototype.getViewMatrix = function () {
  4881. this._computedViewMatrix = this._computeViewMatrix();
  4882. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4883. return this._computedViewMatrix;
  4884. }
  4885. if (!this._worldMatrix) {
  4886. this._worldMatrix = BABYLON.Matrix.Identity();
  4887. }
  4888. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4889. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4890. this._computedViewMatrix.invert();
  4891. this._currentRenderId = this.getScene().getRenderId();
  4892. return this._computedViewMatrix;
  4893. };
  4894. Camera.prototype._computeViewMatrix = function (force) {
  4895. if (!force && this._isSynchronizedViewMatrix()) {
  4896. return this._computedViewMatrix;
  4897. }
  4898. this._computedViewMatrix = this._getViewMatrix();
  4899. if (!this.parent || !this.parent.getWorldMatrix) {
  4900. this._currentRenderId = this.getScene().getRenderId();
  4901. }
  4902. return this._computedViewMatrix;
  4903. };
  4904. Camera.prototype.getProjectionMatrix = function (force) {
  4905. if (!force && this._isSynchronizedProjectionMatrix()) {
  4906. return this._projectionMatrix;
  4907. }
  4908. var engine = this.getEngine();
  4909. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4910. if (this.minZ <= 0) {
  4911. this.minZ = 0.1;
  4912. }
  4913. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4914. return this._projectionMatrix;
  4915. }
  4916. var halfWidth = engine.getRenderWidth() / 2.0;
  4917. var halfHeight = engine.getRenderHeight() / 2.0;
  4918. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4919. return this._projectionMatrix;
  4920. };
  4921. Camera.prototype.dispose = function () {
  4922. var index = this.getScene().cameras.indexOf(this);
  4923. this.getScene().cameras.splice(index, 1);
  4924. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4925. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4926. }
  4927. };
  4928. Camera.PERSPECTIVE_CAMERA = 0;
  4929. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4930. return Camera;
  4931. })(BABYLON.Node);
  4932. BABYLON.Camera = Camera;
  4933. })(BABYLON || (BABYLON = {}));
  4934. var __extends = this.__extends || function (d, b) {
  4935. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4936. function __() { this.constructor = d; }
  4937. __.prototype = b.prototype;
  4938. d.prototype = new __();
  4939. };
  4940. var BABYLON;
  4941. (function (BABYLON) {
  4942. var TargetCamera = (function (_super) {
  4943. __extends(TargetCamera, _super);
  4944. function TargetCamera(name, position, scene) {
  4945. _super.call(this, name, position, scene);
  4946. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4947. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4948. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4949. this.speed = 2.0;
  4950. this.noRotationConstraint = false;
  4951. this.lockedTarget = null;
  4952. this._currentTarget = BABYLON.Vector3.Zero();
  4953. this._viewMatrix = BABYLON.Matrix.Zero();
  4954. this._camMatrix = BABYLON.Matrix.Zero();
  4955. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4956. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4957. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4958. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4959. this._lookAtTemp = BABYLON.Matrix.Zero();
  4960. this._tempMatrix = BABYLON.Matrix.Zero();
  4961. }
  4962. TargetCamera.prototype._getLockedTargetPosition = function () {
  4963. if (!this.lockedTarget) {
  4964. return null;
  4965. }
  4966. return this.lockedTarget.position || this.lockedTarget;
  4967. };
  4968. TargetCamera.prototype._initCache = function () {
  4969. _super.prototype._initCache.call(this);
  4970. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4971. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4972. };
  4973. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4974. if (!ignoreParentClass) {
  4975. _super.prototype._updateCache.call(this);
  4976. }
  4977. var lockedTargetPosition = this._getLockedTargetPosition();
  4978. if (!lockedTargetPosition) {
  4979. this._cache.lockedTarget = null;
  4980. } else {
  4981. if (!this._cache.lockedTarget) {
  4982. this._cache.lockedTarget = lockedTargetPosition.clone();
  4983. } else {
  4984. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  4985. }
  4986. }
  4987. this._cache.rotation.copyFrom(this.rotation);
  4988. };
  4989. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  4990. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  4991. return false;
  4992. }
  4993. var lockedTargetPosition = this._getLockedTargetPosition();
  4994. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  4995. };
  4996. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  4997. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  4998. };
  4999. TargetCamera.prototype.setTarget = function (target) {
  5000. this.upVector.normalize();
  5001. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5002. this._camMatrix.invert();
  5003. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5004. var vDir = target.subtract(this.position);
  5005. if (vDir.x >= 0.0) {
  5006. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5007. } else {
  5008. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5009. }
  5010. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5011. if (isNaN(this.rotation.x)) {
  5012. this.rotation.x = 0;
  5013. }
  5014. if (isNaN(this.rotation.y)) {
  5015. this.rotation.y = 0;
  5016. }
  5017. if (isNaN(this.rotation.z)) {
  5018. this.rotation.z = 0;
  5019. }
  5020. };
  5021. TargetCamera.prototype.getTarget = function () {
  5022. return this._currentTarget;
  5023. };
  5024. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5025. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5026. };
  5027. TargetCamera.prototype._updatePosition = function () {
  5028. this.position.addInPlace(this.cameraDirection);
  5029. };
  5030. TargetCamera.prototype._update = function () {
  5031. var needToMove = this._decideIfNeedsToMove();
  5032. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5033. if (needToMove) {
  5034. this._updatePosition();
  5035. }
  5036. if (needToRotate) {
  5037. this.rotation.x += this.cameraRotation.x;
  5038. this.rotation.y += this.cameraRotation.y;
  5039. if (!this.noRotationConstraint) {
  5040. var limit = (Math.PI / 2) * 0.95;
  5041. if (this.rotation.x > limit)
  5042. this.rotation.x = limit;
  5043. if (this.rotation.x < -limit)
  5044. this.rotation.x = -limit;
  5045. }
  5046. }
  5047. if (needToMove) {
  5048. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5049. this.cameraDirection.x = 0;
  5050. }
  5051. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5052. this.cameraDirection.y = 0;
  5053. }
  5054. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5055. this.cameraDirection.z = 0;
  5056. }
  5057. this.cameraDirection.scaleInPlace(this.inertia);
  5058. }
  5059. if (needToRotate) {
  5060. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5061. this.cameraRotation.x = 0;
  5062. }
  5063. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5064. this.cameraRotation.y = 0;
  5065. }
  5066. this.cameraRotation.scaleInPlace(this.inertia);
  5067. }
  5068. };
  5069. TargetCamera.prototype._getViewMatrix = function () {
  5070. if (!this.lockedTarget) {
  5071. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5072. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5073. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5074. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5075. this._lookAtTemp.invert();
  5076. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5077. } else {
  5078. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5079. }
  5080. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5081. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5082. } else {
  5083. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5084. }
  5085. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5086. return this._viewMatrix;
  5087. };
  5088. return TargetCamera;
  5089. })(BABYLON.Camera);
  5090. BABYLON.TargetCamera = TargetCamera;
  5091. })(BABYLON || (BABYLON = {}));
  5092. var __extends = this.__extends || function (d, b) {
  5093. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5094. function __() { this.constructor = d; }
  5095. __.prototype = b.prototype;
  5096. d.prototype = new __();
  5097. };
  5098. var BABYLON;
  5099. (function (BABYLON) {
  5100. var FollowCamera = (function (_super) {
  5101. __extends(FollowCamera, _super);
  5102. function FollowCamera(name, position, scene) {
  5103. _super.call(this, name, position, scene);
  5104. this.radius = 12;
  5105. this.rotationOffset = 0;
  5106. this.heightOffset = 4;
  5107. this.cameraAcceleration = 0.05;
  5108. this.maxCameraSpeed = 20;
  5109. }
  5110. FollowCamera.prototype.getRadians = function (degrees) {
  5111. return degrees * Math.PI / 180;
  5112. };
  5113. FollowCamera.prototype.follow = function (cameraTarget) {
  5114. if (!cameraTarget)
  5115. return;
  5116. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5117. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5118. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5119. var dx = targetX - this.position.x;
  5120. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5121. var dz = (targetZ) - this.position.z;
  5122. var vx = dx * this.cameraAcceleration * 2;
  5123. var vy = dy * this.cameraAcceleration;
  5124. var vz = dz * this.cameraAcceleration * 2;
  5125. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5126. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5127. }
  5128. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5129. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5130. }
  5131. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5132. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5133. }
  5134. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5135. this.setTarget(cameraTarget.position);
  5136. };
  5137. FollowCamera.prototype._update = function () {
  5138. _super.prototype._update.call(this);
  5139. this.follow(this.target);
  5140. };
  5141. return FollowCamera;
  5142. })(BABYLON.TargetCamera);
  5143. BABYLON.FollowCamera = FollowCamera;
  5144. })(BABYLON || (BABYLON = {}));
  5145. var __extends = this.__extends || function (d, b) {
  5146. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5147. function __() { this.constructor = d; }
  5148. __.prototype = b.prototype;
  5149. d.prototype = new __();
  5150. };
  5151. var BABYLON;
  5152. (function (BABYLON) {
  5153. var FreeCamera = (function (_super) {
  5154. __extends(FreeCamera, _super);
  5155. function FreeCamera(name, position, scene) {
  5156. _super.call(this, name, position, scene);
  5157. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5158. this.keysUp = [38];
  5159. this.keysDown = [40];
  5160. this.keysLeft = [37];
  5161. this.keysRight = [39];
  5162. this.checkCollisions = false;
  5163. this.applyGravity = false;
  5164. this.angularSensibility = 2000.0;
  5165. this._keys = [];
  5166. this._collider = new BABYLON.Collider();
  5167. this._needMoveForGravity = true;
  5168. this._oldPosition = BABYLON.Vector3.Zero();
  5169. this._diffPosition = BABYLON.Vector3.Zero();
  5170. this._newPosition = BABYLON.Vector3.Zero();
  5171. }
  5172. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5173. var _this = this;
  5174. var previousPosition;
  5175. var engine = this.getEngine();
  5176. if (this._attachedElement) {
  5177. return;
  5178. }
  5179. this._attachedElement = element;
  5180. if (this._onMouseDown === undefined) {
  5181. this._onMouseDown = function (evt) {
  5182. previousPosition = {
  5183. x: evt.clientX,
  5184. y: evt.clientY
  5185. };
  5186. if (!noPreventDefault) {
  5187. evt.preventDefault();
  5188. }
  5189. };
  5190. this._onMouseUp = function (evt) {
  5191. previousPosition = null;
  5192. if (!noPreventDefault) {
  5193. evt.preventDefault();
  5194. }
  5195. };
  5196. this._onMouseOut = function (evt) {
  5197. previousPosition = null;
  5198. _this._keys = [];
  5199. if (!noPreventDefault) {
  5200. evt.preventDefault();
  5201. }
  5202. };
  5203. this._onMouseMove = function (evt) {
  5204. if (!previousPosition && !engine.isPointerLock) {
  5205. return;
  5206. }
  5207. var offsetX;
  5208. var offsetY;
  5209. if (!engine.isPointerLock) {
  5210. offsetX = evt.clientX - previousPosition.x;
  5211. offsetY = evt.clientY - previousPosition.y;
  5212. } else {
  5213. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5214. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5215. }
  5216. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5217. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5218. previousPosition = {
  5219. x: evt.clientX,
  5220. y: evt.clientY
  5221. };
  5222. if (!noPreventDefault) {
  5223. evt.preventDefault();
  5224. }
  5225. };
  5226. this._onKeyDown = function (evt) {
  5227. 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) {
  5228. var index = _this._keys.indexOf(evt.keyCode);
  5229. if (index === -1) {
  5230. _this._keys.push(evt.keyCode);
  5231. }
  5232. if (!noPreventDefault) {
  5233. evt.preventDefault();
  5234. }
  5235. }
  5236. };
  5237. this._onKeyUp = function (evt) {
  5238. 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) {
  5239. var index = _this._keys.indexOf(evt.keyCode);
  5240. if (index >= 0) {
  5241. _this._keys.splice(index, 1);
  5242. }
  5243. if (!noPreventDefault) {
  5244. evt.preventDefault();
  5245. }
  5246. }
  5247. };
  5248. this._onLostFocus = function () {
  5249. _this._keys = [];
  5250. };
  5251. this._reset = function () {
  5252. _this._keys = [];
  5253. previousPosition = null;
  5254. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5255. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5256. };
  5257. }
  5258. element.addEventListener("mousedown", this._onMouseDown, false);
  5259. element.addEventListener("mouseup", this._onMouseUp, false);
  5260. element.addEventListener("mouseout", this._onMouseOut, false);
  5261. element.addEventListener("mousemove", this._onMouseMove, false);
  5262. BABYLON.Tools.RegisterTopRootEvents([
  5263. { name: "keydown", handler: this._onKeyDown },
  5264. { name: "keyup", handler: this._onKeyUp },
  5265. { name: "blur", handler: this._onLostFocus }
  5266. ]);
  5267. };
  5268. FreeCamera.prototype.detachControl = function (element) {
  5269. if (this._attachedElement != element) {
  5270. return;
  5271. }
  5272. element.removeEventListener("mousedown", this._onMouseDown);
  5273. element.removeEventListener("mouseup", this._onMouseUp);
  5274. element.removeEventListener("mouseout", this._onMouseOut);
  5275. element.removeEventListener("mousemove", this._onMouseMove);
  5276. BABYLON.Tools.UnregisterTopRootEvents([
  5277. { name: "keydown", handler: this._onKeyDown },
  5278. { name: "keyup", handler: this._onKeyUp },
  5279. { name: "blur", handler: this._onLostFocus }
  5280. ]);
  5281. this._attachedElement = null;
  5282. if (this._reset) {
  5283. this._reset();
  5284. }
  5285. };
  5286. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5287. var globalPosition;
  5288. if (this.parent) {
  5289. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5290. } else {
  5291. globalPosition = this.position;
  5292. }
  5293. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5294. this._collider.radius = this.ellipsoid;
  5295. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5296. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5297. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5298. this.position.addInPlace(this._diffPosition);
  5299. if (this.onCollide) {
  5300. this.onCollide(this._collider.collidedMesh);
  5301. }
  5302. }
  5303. };
  5304. FreeCamera.prototype._checkInputs = function () {
  5305. if (!this._localDirection) {
  5306. this._localDirection = BABYLON.Vector3.Zero();
  5307. this._transformedDirection = BABYLON.Vector3.Zero();
  5308. }
  5309. for (var index = 0; index < this._keys.length; index++) {
  5310. var keyCode = this._keys[index];
  5311. var speed = this._computeLocalCameraSpeed();
  5312. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5313. this._localDirection.copyFromFloats(-speed, 0, 0);
  5314. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5315. this._localDirection.copyFromFloats(0, 0, speed);
  5316. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5317. this._localDirection.copyFromFloats(speed, 0, 0);
  5318. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5319. this._localDirection.copyFromFloats(0, 0, -speed);
  5320. }
  5321. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5322. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5323. this.cameraDirection.addInPlace(this._transformedDirection);
  5324. }
  5325. };
  5326. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5327. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5328. };
  5329. FreeCamera.prototype._updatePosition = function () {
  5330. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5331. this._collideWithWorld(this.cameraDirection);
  5332. if (this.applyGravity) {
  5333. var oldPosition = this.position;
  5334. this._collideWithWorld(this.getScene().gravity);
  5335. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5336. }
  5337. } else {
  5338. this.position.addInPlace(this.cameraDirection);
  5339. }
  5340. };
  5341. FreeCamera.prototype._update = function () {
  5342. this._checkInputs();
  5343. _super.prototype._update.call(this);
  5344. };
  5345. return FreeCamera;
  5346. })(BABYLON.TargetCamera);
  5347. BABYLON.FreeCamera = FreeCamera;
  5348. })(BABYLON || (BABYLON = {}));
  5349. var __extends = this.__extends || function (d, b) {
  5350. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5351. function __() { this.constructor = d; }
  5352. __.prototype = b.prototype;
  5353. d.prototype = new __();
  5354. };
  5355. var BABYLON;
  5356. (function (BABYLON) {
  5357. var TouchCamera = (function (_super) {
  5358. __extends(TouchCamera, _super);
  5359. function TouchCamera(name, position, scene) {
  5360. _super.call(this, name, position, scene);
  5361. this._offsetX = null;
  5362. this._offsetY = null;
  5363. this._pointerCount = 0;
  5364. this._pointerPressed = [];
  5365. this.angularSensibility = 200000.0;
  5366. this.moveSensibility = 500.0;
  5367. }
  5368. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5369. var _this = this;
  5370. var previousPosition;
  5371. if (this._attachedCanvas) {
  5372. return;
  5373. }
  5374. this._attachedCanvas = canvas;
  5375. if (this._onPointerDown === undefined) {
  5376. this._onPointerDown = function (evt) {
  5377. if (!noPreventDefault) {
  5378. evt.preventDefault();
  5379. }
  5380. _this._pointerPressed.push(evt.pointerId);
  5381. if (_this._pointerPressed.length !== 1) {
  5382. return;
  5383. }
  5384. previousPosition = {
  5385. x: evt.clientX,
  5386. y: evt.clientY
  5387. };
  5388. };
  5389. this._onPointerUp = function (evt) {
  5390. if (!noPreventDefault) {
  5391. evt.preventDefault();
  5392. }
  5393. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5394. if (index === -1) {
  5395. return;
  5396. }
  5397. _this._pointerPressed.splice(index, 1);
  5398. if (index != 0) {
  5399. return;
  5400. }
  5401. previousPosition = null;
  5402. _this._offsetX = null;
  5403. _this._offsetY = null;
  5404. };
  5405. this._onPointerMove = function (evt) {
  5406. if (!noPreventDefault) {
  5407. evt.preventDefault();
  5408. }
  5409. if (!previousPosition) {
  5410. return;
  5411. }
  5412. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5413. if (index != 0) {
  5414. return;
  5415. }
  5416. _this._offsetX = evt.clientX - previousPosition.x;
  5417. _this._offsetY = -(evt.clientY - previousPosition.y);
  5418. };
  5419. this._onLostFocus = function () {
  5420. _this._offsetX = null;
  5421. _this._offsetY = null;
  5422. };
  5423. }
  5424. canvas.addEventListener("pointerdown", this._onPointerDown);
  5425. canvas.addEventListener("pointerup", this._onPointerUp);
  5426. canvas.addEventListener("pointerout", this._onPointerUp);
  5427. canvas.addEventListener("pointermove", this._onPointerMove);
  5428. BABYLON.Tools.RegisterTopRootEvents([
  5429. { name: "blur", handler: this._onLostFocus }
  5430. ]);
  5431. };
  5432. TouchCamera.prototype.detachControl = function (canvas) {
  5433. if (this._attachedCanvas != canvas) {
  5434. return;
  5435. }
  5436. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5437. canvas.removeEventListener("pointerup", this._onPointerUp);
  5438. canvas.removeEventListener("pointerout", this._onPointerUp);
  5439. canvas.removeEventListener("pointermove", this._onPointerMove);
  5440. BABYLON.Tools.UnregisterTopRootEvents([
  5441. { name: "blur", handler: this._onLostFocus }
  5442. ]);
  5443. this._attachedCanvas = null;
  5444. };
  5445. TouchCamera.prototype._checkInputs = function () {
  5446. if (!this._offsetX) {
  5447. return;
  5448. }
  5449. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5450. if (this._pointerPressed.length > 1) {
  5451. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5452. } else {
  5453. var speed = this._computeLocalCameraSpeed();
  5454. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5455. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5456. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5457. }
  5458. };
  5459. return TouchCamera;
  5460. })(BABYLON.FreeCamera);
  5461. BABYLON.TouchCamera = TouchCamera;
  5462. })(BABYLON || (BABYLON = {}));
  5463. var __extends = this.__extends || function (d, b) {
  5464. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5465. function __() { this.constructor = d; }
  5466. __.prototype = b.prototype;
  5467. d.prototype = new __();
  5468. };
  5469. var BABYLON;
  5470. (function (BABYLON) {
  5471. var DeviceOrientationCamera = (function (_super) {
  5472. __extends(DeviceOrientationCamera, _super);
  5473. function DeviceOrientationCamera(name, position, scene) {
  5474. var _this = this;
  5475. _super.call(this, name, position, scene);
  5476. this._offsetX = null;
  5477. this._offsetY = null;
  5478. this._orientationGamma = 0;
  5479. this._orientationBeta = 0;
  5480. this._initialOrientationGamma = 0;
  5481. this._initialOrientationBeta = 0;
  5482. this.angularSensibility = 10000.0;
  5483. this.moveSensibility = 50.0;
  5484. window.addEventListener("resize", function () {
  5485. _this._initialOrientationGamma = null;
  5486. }, false);
  5487. }
  5488. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5489. var _this = this;
  5490. if (this._attachedCanvas) {
  5491. return;
  5492. }
  5493. this._attachedCanvas = canvas;
  5494. if (!this._orientationChanged) {
  5495. this._orientationChanged = function (evt) {
  5496. if (!_this._initialOrientationGamma) {
  5497. _this._initialOrientationGamma = evt.gamma;
  5498. _this._initialOrientationBeta = evt.beta;
  5499. }
  5500. _this._orientationGamma = evt.gamma;
  5501. _this._orientationBeta = evt.beta;
  5502. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5503. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5504. };
  5505. }
  5506. window.addEventListener("deviceorientation", this._orientationChanged);
  5507. };
  5508. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5509. if (this._attachedCanvas != canvas) {
  5510. return;
  5511. }
  5512. window.removeEventListener("deviceorientation", this._orientationChanged);
  5513. this._attachedCanvas = null;
  5514. this._orientationGamma = 0;
  5515. this._orientationBeta = 0;
  5516. this._initialOrientationGamma = 0;
  5517. this._initialOrientationBeta = 0;
  5518. };
  5519. DeviceOrientationCamera.prototype._checkInputs = function () {
  5520. if (!this._offsetX) {
  5521. return;
  5522. }
  5523. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5524. var speed = this._computeLocalCameraSpeed();
  5525. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5526. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5527. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5528. };
  5529. return DeviceOrientationCamera;
  5530. })(BABYLON.FreeCamera);
  5531. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5532. })(BABYLON || (BABYLON = {}));
  5533. var __extends = this.__extends || function (d, b) {
  5534. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5535. function __() { this.constructor = d; }
  5536. __.prototype = b.prototype;
  5537. d.prototype = new __();
  5538. };
  5539. var BABYLON;
  5540. (function (BABYLON) {
  5541. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5542. var ArcRotateCamera = (function (_super) {
  5543. __extends(ArcRotateCamera, _super);
  5544. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5545. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5546. this.alpha = alpha;
  5547. this.beta = beta;
  5548. this.radius = radius;
  5549. this.target = target;
  5550. this.inertialAlphaOffset = 0;
  5551. this.inertialBetaOffset = 0;
  5552. this.inertialRadiusOffset = 0;
  5553. this.lowerAlphaLimit = null;
  5554. this.upperAlphaLimit = null;
  5555. this.lowerBetaLimit = 0.01;
  5556. this.upperBetaLimit = Math.PI;
  5557. this.lowerRadiusLimit = null;
  5558. this.upperRadiusLimit = null;
  5559. this.angularSensibility = 1000.0;
  5560. this.wheelPrecision = 3.0;
  5561. this.keysUp = [38];
  5562. this.keysDown = [40];
  5563. this.keysLeft = [37];
  5564. this.keysRight = [39];
  5565. this.zoomOnFactor = 1;
  5566. this._keys = [];
  5567. this._viewMatrix = new BABYLON.Matrix();
  5568. this.checkCollisions = false;
  5569. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5570. this._collider = new BABYLON.Collider();
  5571. this._previousPosition = BABYLON.Vector3.Zero();
  5572. this._collisionVelocity = BABYLON.Vector3.Zero();
  5573. this._newPosition = BABYLON.Vector3.Zero();
  5574. this.getViewMatrix();
  5575. }
  5576. ArcRotateCamera.prototype._getTargetPosition = function () {
  5577. return this.target.position || this.target;
  5578. };
  5579. ArcRotateCamera.prototype._initCache = function () {
  5580. _super.prototype._initCache.call(this);
  5581. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5582. this._cache.alpha = undefined;
  5583. this._cache.beta = undefined;
  5584. this._cache.radius = undefined;
  5585. };
  5586. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5587. if (!ignoreParentClass) {
  5588. _super.prototype._updateCache.call(this);
  5589. }
  5590. this._cache.target.copyFrom(this._getTargetPosition());
  5591. this._cache.alpha = this.alpha;
  5592. this._cache.beta = this.beta;
  5593. this._cache.radius = this.radius;
  5594. };
  5595. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5596. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5597. return false;
  5598. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5599. };
  5600. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5601. var _this = this;
  5602. var previousPosition;
  5603. var pointerId;
  5604. if (this._attachedElement) {
  5605. return;
  5606. }
  5607. this._attachedElement = element;
  5608. var engine = this.getEngine();
  5609. if (this._onPointerDown === undefined) {
  5610. this._onPointerDown = function (evt) {
  5611. if (pointerId) {
  5612. return;
  5613. }
  5614. pointerId = evt.pointerId;
  5615. previousPosition = {
  5616. x: evt.clientX,
  5617. y: evt.clientY
  5618. };
  5619. if (!noPreventDefault) {
  5620. evt.preventDefault();
  5621. }
  5622. };
  5623. this._onPointerUp = function (evt) {
  5624. previousPosition = null;
  5625. pointerId = null;
  5626. if (!noPreventDefault) {
  5627. evt.preventDefault();
  5628. }
  5629. };
  5630. this._onPointerMove = function (evt) {
  5631. if (!previousPosition) {
  5632. return;
  5633. }
  5634. if (pointerId !== evt.pointerId) {
  5635. return;
  5636. }
  5637. var offsetX = evt.clientX - previousPosition.x;
  5638. var offsetY = evt.clientY - previousPosition.y;
  5639. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5640. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5641. previousPosition = {
  5642. x: evt.clientX,
  5643. y: evt.clientY
  5644. };
  5645. if (!noPreventDefault) {
  5646. evt.preventDefault();
  5647. }
  5648. };
  5649. this._onMouseMove = function (evt) {
  5650. if (!engine.isPointerLock) {
  5651. return;
  5652. }
  5653. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5654. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5655. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5656. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5657. if (!noPreventDefault) {
  5658. evt.preventDefault();
  5659. }
  5660. };
  5661. this._wheel = function (event) {
  5662. var delta = 0;
  5663. if (event.wheelDelta) {
  5664. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5665. } else if (event.detail) {
  5666. delta = -event.detail / _this.wheelPrecision;
  5667. }
  5668. if (delta)
  5669. _this.inertialRadiusOffset += delta;
  5670. if (event.preventDefault) {
  5671. if (!noPreventDefault) {
  5672. event.preventDefault();
  5673. }
  5674. }
  5675. };
  5676. this._onKeyDown = function (evt) {
  5677. 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) {
  5678. var index = _this._keys.indexOf(evt.keyCode);
  5679. if (index === -1) {
  5680. _this._keys.push(evt.keyCode);
  5681. }
  5682. if (evt.preventDefault) {
  5683. if (!noPreventDefault) {
  5684. evt.preventDefault();
  5685. }
  5686. }
  5687. }
  5688. };
  5689. this._onKeyUp = function (evt) {
  5690. 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) {
  5691. var index = _this._keys.indexOf(evt.keyCode);
  5692. if (index >= 0) {
  5693. _this._keys.splice(index, 1);
  5694. }
  5695. if (evt.preventDefault) {
  5696. if (!noPreventDefault) {
  5697. evt.preventDefault();
  5698. }
  5699. }
  5700. }
  5701. };
  5702. this._onLostFocus = function () {
  5703. _this._keys = [];
  5704. pointerId = null;
  5705. };
  5706. this._onGestureStart = function (e) {
  5707. if (window.MSGesture === undefined) {
  5708. return;
  5709. }
  5710. if (!_this._MSGestureHandler) {
  5711. _this._MSGestureHandler = new MSGesture();
  5712. _this._MSGestureHandler.target = element;
  5713. }
  5714. _this._MSGestureHandler.addPointer(e.pointerId);
  5715. };
  5716. this._onGesture = function (e) {
  5717. _this.radius *= e.scale;
  5718. if (e.preventDefault) {
  5719. if (!noPreventDefault) {
  5720. e.stopPropagation();
  5721. e.preventDefault();
  5722. }
  5723. }
  5724. };
  5725. this._reset = function () {
  5726. _this._keys = [];
  5727. _this.inertialAlphaOffset = 0;
  5728. _this.inertialBetaOffset = 0;
  5729. _this.inertialRadiusOffset = 0;
  5730. previousPosition = null;
  5731. pointerId = null;
  5732. };
  5733. }
  5734. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5735. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5736. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5737. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5738. element.addEventListener("mousemove", this._onMouseMove, false);
  5739. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5740. element.addEventListener("MSGestureChange", this._onGesture, false);
  5741. element.addEventListener('mousewheel', this._wheel, false);
  5742. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5743. BABYLON.Tools.RegisterTopRootEvents([
  5744. { name: "keydown", handler: this._onKeyDown },
  5745. { name: "keyup", handler: this._onKeyUp },
  5746. { name: "blur", handler: this._onLostFocus }
  5747. ]);
  5748. };
  5749. ArcRotateCamera.prototype.detachControl = function (element) {
  5750. if (this._attachedElement != element) {
  5751. return;
  5752. }
  5753. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5754. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5755. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5756. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5757. element.removeEventListener("mousemove", this._onMouseMove);
  5758. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5759. element.removeEventListener("MSGestureChange", this._onGesture);
  5760. element.removeEventListener('mousewheel', this._wheel);
  5761. element.removeEventListener('DOMMouseScroll', this._wheel);
  5762. BABYLON.Tools.UnregisterTopRootEvents([
  5763. { name: "keydown", handler: this._onKeyDown },
  5764. { name: "keyup", handler: this._onKeyUp },
  5765. { name: "blur", handler: this._onLostFocus }
  5766. ]);
  5767. this._MSGestureHandler = null;
  5768. this._attachedElement = null;
  5769. if (this._reset) {
  5770. this._reset();
  5771. }
  5772. };
  5773. ArcRotateCamera.prototype._update = function () {
  5774. for (var index = 0; index < this._keys.length; index++) {
  5775. var keyCode = this._keys[index];
  5776. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5777. this.inertialAlphaOffset -= 0.01;
  5778. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5779. this.inertialBetaOffset -= 0.01;
  5780. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5781. this.inertialAlphaOffset += 0.01;
  5782. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5783. this.inertialBetaOffset += 0.01;
  5784. }
  5785. }
  5786. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5787. this.alpha += this.inertialAlphaOffset;
  5788. this.beta += this.inertialBetaOffset;
  5789. this.radius -= this.inertialRadiusOffset;
  5790. this.inertialAlphaOffset *= this.inertia;
  5791. this.inertialBetaOffset *= this.inertia;
  5792. this.inertialRadiusOffset *= this.inertia;
  5793. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5794. this.inertialAlphaOffset = 0;
  5795. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5796. this.inertialBetaOffset = 0;
  5797. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5798. this.inertialRadiusOffset = 0;
  5799. }
  5800. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5801. this.alpha = this.lowerAlphaLimit;
  5802. }
  5803. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5804. this.alpha = this.upperAlphaLimit;
  5805. }
  5806. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5807. this.beta = this.lowerBetaLimit;
  5808. }
  5809. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5810. this.beta = this.upperBetaLimit;
  5811. }
  5812. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5813. this.radius = this.lowerRadiusLimit;
  5814. }
  5815. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5816. this.radius = this.upperRadiusLimit;
  5817. }
  5818. };
  5819. ArcRotateCamera.prototype.setPosition = function (position) {
  5820. var radiusv3 = position.subtract(this._getTargetPosition());
  5821. this.radius = radiusv3.length();
  5822. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5823. if (radiusv3.z < 0) {
  5824. this.alpha = 2 * Math.PI - this.alpha;
  5825. }
  5826. this.beta = Math.acos(radiusv3.y / this.radius);
  5827. };
  5828. ArcRotateCamera.prototype._getViewMatrix = function () {
  5829. var cosa = Math.cos(this.alpha);
  5830. var sina = Math.sin(this.alpha);
  5831. var cosb = Math.cos(this.beta);
  5832. var sinb = Math.sin(this.beta);
  5833. var target = this._getTargetPosition();
  5834. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5835. if (this.checkCollisions) {
  5836. this._collider.radius = this.collisionRadius;
  5837. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5838. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5839. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5840. this.position.copyFrom(this._previousPosition);
  5841. this.alpha = this._previousAlpha;
  5842. this.beta = this._previousBeta;
  5843. this.radius = this._previousRadius;
  5844. if (this.onCollide) {
  5845. this.onCollide(this._collider.collidedMesh);
  5846. }
  5847. }
  5848. }
  5849. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5850. this._previousAlpha = this.alpha;
  5851. this._previousBeta = this.beta;
  5852. this._previousRadius = this.radius;
  5853. this._previousPosition.copyFrom(this.position);
  5854. return this._viewMatrix;
  5855. };
  5856. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5857. meshes = meshes || this.getScene().meshes;
  5858. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5859. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5860. this.radius = distance * this.zoomOnFactor;
  5861. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5862. };
  5863. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5864. var meshesOrMinMaxVector;
  5865. var distance;
  5866. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5867. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5868. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5869. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5870. } else {
  5871. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5872. distance = meshesOrMinMaxVectorAndDistance.distance;
  5873. }
  5874. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5875. this.maxZ = distance * 2;
  5876. };
  5877. return ArcRotateCamera;
  5878. })(BABYLON.Camera);
  5879. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5880. })(BABYLON || (BABYLON = {}));
  5881. var BABYLON;
  5882. (function (BABYLON) {
  5883. var Scene = (function () {
  5884. function Scene(engine) {
  5885. this.autoClear = true;
  5886. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5887. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5888. this.forceWireframe = false;
  5889. this.cameraToUseForPointers = null;
  5890. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5891. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5892. this.fogDensity = 0.1;
  5893. this.fogStart = 0;
  5894. this.fogEnd = 1000.0;
  5895. this.lightsEnabled = true;
  5896. this.lights = new Array();
  5897. this.cameras = new Array();
  5898. this.activeCameras = new Array();
  5899. this.meshes = new Array();
  5900. this._geometries = new Array();
  5901. this.materials = new Array();
  5902. this.multiMaterials = new Array();
  5903. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5904. this.texturesEnabled = true;
  5905. this.textures = new Array();
  5906. this.particlesEnabled = true;
  5907. this.particleSystems = new Array();
  5908. this.spriteManagers = new Array();
  5909. this.layers = new Array();
  5910. this.skeletons = new Array();
  5911. this.lensFlareSystems = new Array();
  5912. this.collisionsEnabled = true;
  5913. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5914. this.postProcessesEnabled = true;
  5915. this.renderTargetsEnabled = true;
  5916. this.customRenderTargets = new Array();
  5917. this.importedMeshesFiles = new Array();
  5918. this._actionManagers = new Array();
  5919. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5920. this._totalVertices = 0;
  5921. this._activeVertices = 0;
  5922. this._activeParticles = 0;
  5923. this._lastFrameDuration = 0;
  5924. this._evaluateActiveMeshesDuration = 0;
  5925. this._renderTargetsDuration = 0;
  5926. this._particlesDuration = 0;
  5927. this._renderDuration = 0;
  5928. this._spritesDuration = 0;
  5929. this._animationRatio = 0;
  5930. this._renderId = 0;
  5931. this._executeWhenReadyTimeoutId = -1;
  5932. this._toBeDisposed = new BABYLON.SmartArray(256);
  5933. this._onReadyCallbacks = new Array();
  5934. this._pendingData = [];
  5935. this._onBeforeRenderCallbacks = new Array();
  5936. this._activeMeshes = new BABYLON.SmartArray(256);
  5937. this._processedMaterials = new BABYLON.SmartArray(256);
  5938. this._renderTargets = new BABYLON.SmartArray(256);
  5939. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5940. this._activeSkeletons = new BABYLON.SmartArray(32);
  5941. this._activeAnimatables = new Array();
  5942. this._transformMatrix = BABYLON.Matrix.Zero();
  5943. this._scaledPosition = BABYLON.Vector3.Zero();
  5944. this._scaledVelocity = BABYLON.Vector3.Zero();
  5945. this._engine = engine;
  5946. engine.scenes.push(this);
  5947. this._renderingManager = new BABYLON.RenderingManager(this);
  5948. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5949. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5950. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5951. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5952. this.attachControl();
  5953. }
  5954. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5955. get: function () {
  5956. return this._meshUnderPointer;
  5957. },
  5958. enumerable: true,
  5959. configurable: true
  5960. });
  5961. Object.defineProperty(Scene.prototype, "pointerX", {
  5962. get: function () {
  5963. return this._pointerX;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(Scene.prototype, "pointerY", {
  5969. get: function () {
  5970. return this._pointerY;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. Scene.prototype.getBoundingBoxRenderer = function () {
  5976. return this._boundingBoxRenderer;
  5977. };
  5978. Scene.prototype.getOutlineRenderer = function () {
  5979. return this._outlineRenderer;
  5980. };
  5981. Scene.prototype.getEngine = function () {
  5982. return this._engine;
  5983. };
  5984. Scene.prototype.getTotalVertices = function () {
  5985. return this._totalVertices;
  5986. };
  5987. Scene.prototype.getActiveVertices = function () {
  5988. return this._activeVertices;
  5989. };
  5990. Scene.prototype.getActiveParticles = function () {
  5991. return this._activeParticles;
  5992. };
  5993. Scene.prototype.getLastFrameDuration = function () {
  5994. return this._lastFrameDuration;
  5995. };
  5996. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  5997. return this._evaluateActiveMeshesDuration;
  5998. };
  5999. Scene.prototype.getActiveMeshes = function () {
  6000. return this._activeMeshes;
  6001. };
  6002. Scene.prototype.getRenderTargetsDuration = function () {
  6003. return this._renderTargetsDuration;
  6004. };
  6005. Scene.prototype.getRenderDuration = function () {
  6006. return this._renderDuration;
  6007. };
  6008. Scene.prototype.getParticlesDuration = function () {
  6009. return this._particlesDuration;
  6010. };
  6011. Scene.prototype.getSpritesDuration = function () {
  6012. return this._spritesDuration;
  6013. };
  6014. Scene.prototype.getAnimationRatio = function () {
  6015. return this._animationRatio;
  6016. };
  6017. Scene.prototype.getRenderId = function () {
  6018. return this._renderId;
  6019. };
  6020. Scene.prototype._updatePointerPosition = function (evt) {
  6021. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6022. this._pointerX = evt.clientX - canvasRect.left;
  6023. this._pointerY = evt.clientY - canvasRect.top;
  6024. if (this.cameraToUseForPointers) {
  6025. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6026. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6027. }
  6028. };
  6029. Scene.prototype.attachControl = function () {
  6030. var _this = this;
  6031. this._onPointerMove = function (evt) {
  6032. var canvas = _this._engine.getRenderingCanvas();
  6033. _this._updatePointerPosition(evt);
  6034. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6035. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6036. }, false, _this.cameraToUseForPointers);
  6037. if (pickResult.hit) {
  6038. _this._meshUnderPointer = pickResult.pickedMesh;
  6039. _this.setPointerOverMesh(pickResult.pickedMesh);
  6040. canvas.style.cursor = "pointer";
  6041. } else {
  6042. _this.setPointerOverMesh(null);
  6043. canvas.style.cursor = "";
  6044. _this._meshUnderPointer = null;
  6045. }
  6046. };
  6047. this._onPointerDown = function (evt) {
  6048. var predicate = null;
  6049. if (!_this.onPointerDown) {
  6050. predicate = function (mesh) {
  6051. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6052. };
  6053. }
  6054. _this._updatePointerPosition(evt);
  6055. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6056. if (pickResult.hit) {
  6057. if (pickResult.pickedMesh.actionManager) {
  6058. switch (evt.button) {
  6059. case 0:
  6060. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6061. break;
  6062. case 1:
  6063. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6064. break;
  6065. case 2:
  6066. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6067. break;
  6068. }
  6069. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6070. }
  6071. }
  6072. if (_this.onPointerDown) {
  6073. _this.onPointerDown(evt, pickResult);
  6074. }
  6075. };
  6076. this._onKeyDown = function (evt) {
  6077. if (_this.actionManager) {
  6078. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6079. }
  6080. };
  6081. this._onKeyUp = function (evt) {
  6082. if (_this.actionManager) {
  6083. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6084. }
  6085. };
  6086. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6087. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6088. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6089. window.addEventListener("keydown", this._onKeyDown, false);
  6090. window.addEventListener("keyup", this._onKeyUp, false);
  6091. };
  6092. Scene.prototype.detachControl = function () {
  6093. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6094. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6095. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6096. window.removeEventListener("keydown", this._onKeyDown);
  6097. window.removeEventListener("keyup", this._onKeyUp);
  6098. };
  6099. Scene.prototype.isReady = function () {
  6100. if (this._pendingData.length > 0) {
  6101. return false;
  6102. }
  6103. for (var index = 0; index < this._geometries.length; index++) {
  6104. var geometry = this._geometries[index];
  6105. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6106. return false;
  6107. }
  6108. }
  6109. for (index = 0; index < this.meshes.length; index++) {
  6110. var mesh = this.meshes[index];
  6111. if (!mesh.isReady()) {
  6112. return false;
  6113. }
  6114. var mat = mesh.material;
  6115. if (mat) {
  6116. if (!mat.isReady(mesh)) {
  6117. return false;
  6118. }
  6119. }
  6120. }
  6121. return true;
  6122. };
  6123. Scene.prototype.registerBeforeRender = function (func) {
  6124. this._onBeforeRenderCallbacks.push(func);
  6125. };
  6126. Scene.prototype.unregisterBeforeRender = function (func) {
  6127. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6128. if (index > -1) {
  6129. this._onBeforeRenderCallbacks.splice(index, 1);
  6130. }
  6131. };
  6132. Scene.prototype._addPendingData = function (data) {
  6133. this._pendingData.push(data);
  6134. };
  6135. Scene.prototype._removePendingData = function (data) {
  6136. var index = this._pendingData.indexOf(data);
  6137. if (index !== -1) {
  6138. this._pendingData.splice(index, 1);
  6139. }
  6140. };
  6141. Scene.prototype.getWaitingItemsCount = function () {
  6142. return this._pendingData.length;
  6143. };
  6144. Scene.prototype.executeWhenReady = function (func) {
  6145. var _this = this;
  6146. this._onReadyCallbacks.push(func);
  6147. if (this._executeWhenReadyTimeoutId !== -1) {
  6148. return;
  6149. }
  6150. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6151. _this._checkIsReady();
  6152. }, 150);
  6153. };
  6154. Scene.prototype._checkIsReady = function () {
  6155. var _this = this;
  6156. if (this.isReady()) {
  6157. this._onReadyCallbacks.forEach(function (func) {
  6158. func();
  6159. });
  6160. this._onReadyCallbacks = [];
  6161. this._executeWhenReadyTimeoutId = -1;
  6162. return;
  6163. }
  6164. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6165. _this._checkIsReady();
  6166. }, 150);
  6167. };
  6168. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6169. if (speedRatio === undefined) {
  6170. speedRatio = 1.0;
  6171. }
  6172. this.stopAnimation(target);
  6173. if (!animatable) {
  6174. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6175. }
  6176. if (target.animations) {
  6177. animatable.appendAnimations(target, target.animations);
  6178. }
  6179. if (target.getAnimatables) {
  6180. var animatables = target.getAnimatables();
  6181. for (var index = 0; index < animatables.length; index++) {
  6182. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6183. }
  6184. }
  6185. return animatable;
  6186. };
  6187. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6188. if (speedRatio === undefined) {
  6189. speedRatio = 1.0;
  6190. }
  6191. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6192. return animatable;
  6193. };
  6194. Scene.prototype.getAnimatableByTarget = function (target) {
  6195. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6196. if (this._activeAnimatables[index].target === target) {
  6197. return this._activeAnimatables[index];
  6198. }
  6199. }
  6200. return null;
  6201. };
  6202. Scene.prototype.stopAnimation = function (target) {
  6203. var animatable = this.getAnimatableByTarget(target);
  6204. if (animatable) {
  6205. animatable.stop();
  6206. }
  6207. };
  6208. Scene.prototype._animate = function () {
  6209. if (!this._animationStartDate) {
  6210. this._animationStartDate = new Date().getTime();
  6211. }
  6212. var now = new Date().getTime();
  6213. var delay = now - this._animationStartDate;
  6214. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6215. if (!this._activeAnimatables[index]._animate(delay)) {
  6216. this._activeAnimatables.splice(index, 1);
  6217. index--;
  6218. }
  6219. }
  6220. };
  6221. Scene.prototype.getViewMatrix = function () {
  6222. return this._viewMatrix;
  6223. };
  6224. Scene.prototype.getProjectionMatrix = function () {
  6225. return this._projectionMatrix;
  6226. };
  6227. Scene.prototype.getTransformMatrix = function () {
  6228. return this._transformMatrix;
  6229. };
  6230. Scene.prototype.setTransformMatrix = function (view, projection) {
  6231. this._viewMatrix = view;
  6232. this._projectionMatrix = projection;
  6233. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6234. };
  6235. Scene.prototype.setActiveCameraByID = function (id) {
  6236. var camera = this.getCameraByID(id);
  6237. if (camera) {
  6238. this.activeCamera = camera;
  6239. return camera;
  6240. }
  6241. return null;
  6242. };
  6243. Scene.prototype.setActiveCameraByName = function (name) {
  6244. var camera = this.getCameraByName(name);
  6245. if (camera) {
  6246. this.activeCamera = camera;
  6247. return camera;
  6248. }
  6249. return null;
  6250. };
  6251. Scene.prototype.getMaterialByID = function (id) {
  6252. for (var index = 0; index < this.materials.length; index++) {
  6253. if (this.materials[index].id === id) {
  6254. return this.materials[index];
  6255. }
  6256. }
  6257. return null;
  6258. };
  6259. Scene.prototype.getMaterialByName = function (name) {
  6260. for (var index = 0; index < this.materials.length; index++) {
  6261. if (this.materials[index].name === name) {
  6262. return this.materials[index];
  6263. }
  6264. }
  6265. return null;
  6266. };
  6267. Scene.prototype.getCameraByID = function (id) {
  6268. for (var index = 0; index < this.cameras.length; index++) {
  6269. if (this.cameras[index].id === id) {
  6270. return this.cameras[index];
  6271. }
  6272. }
  6273. return null;
  6274. };
  6275. Scene.prototype.getCameraByName = function (name) {
  6276. for (var index = 0; index < this.cameras.length; index++) {
  6277. if (this.cameras[index].name === name) {
  6278. return this.cameras[index];
  6279. }
  6280. }
  6281. return null;
  6282. };
  6283. Scene.prototype.getLightByName = function (name) {
  6284. for (var index = 0; index < this.lights.length; index++) {
  6285. if (this.lights[index].name === name) {
  6286. return this.lights[index];
  6287. }
  6288. }
  6289. return null;
  6290. };
  6291. Scene.prototype.getLightByID = function (id) {
  6292. for (var index = 0; index < this.lights.length; index++) {
  6293. if (this.lights[index].id === id) {
  6294. return this.lights[index];
  6295. }
  6296. }
  6297. return null;
  6298. };
  6299. Scene.prototype.getGeometryByID = function (id) {
  6300. for (var index = 0; index < this._geometries.length; index++) {
  6301. if (this._geometries[index].id === id) {
  6302. return this._geometries[index];
  6303. }
  6304. }
  6305. return null;
  6306. };
  6307. Scene.prototype.pushGeometry = function (geometry, force) {
  6308. if (!force && this.getGeometryByID(geometry.id)) {
  6309. return false;
  6310. }
  6311. this._geometries.push(geometry);
  6312. return true;
  6313. };
  6314. Scene.prototype.getGeometries = function () {
  6315. return this._geometries;
  6316. };
  6317. Scene.prototype.getMeshByID = function (id) {
  6318. for (var index = 0; index < this.meshes.length; index++) {
  6319. if (this.meshes[index].id === id) {
  6320. return this.meshes[index];
  6321. }
  6322. }
  6323. return null;
  6324. };
  6325. Scene.prototype.getLastMeshByID = function (id) {
  6326. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6327. if (this.meshes[index].id === id) {
  6328. return this.meshes[index];
  6329. }
  6330. }
  6331. return null;
  6332. };
  6333. Scene.prototype.getLastEntryByID = function (id) {
  6334. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6335. if (this.meshes[index].id === id) {
  6336. return this.meshes[index];
  6337. }
  6338. }
  6339. for (index = this.cameras.length - 1; index >= 0; index--) {
  6340. if (this.cameras[index].id === id) {
  6341. return this.cameras[index];
  6342. }
  6343. }
  6344. for (index = this.lights.length - 1; index >= 0; index--) {
  6345. if (this.lights[index].id === id) {
  6346. return this.lights[index];
  6347. }
  6348. }
  6349. return null;
  6350. };
  6351. Scene.prototype.getMeshByName = function (name) {
  6352. for (var index = 0; index < this.meshes.length; index++) {
  6353. if (this.meshes[index].name === name) {
  6354. return this.meshes[index];
  6355. }
  6356. }
  6357. return null;
  6358. };
  6359. Scene.prototype.getLastSkeletonByID = function (id) {
  6360. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6361. if (this.skeletons[index].id === id) {
  6362. return this.skeletons[index];
  6363. }
  6364. }
  6365. return null;
  6366. };
  6367. Scene.prototype.getSkeletonById = function (id) {
  6368. for (var index = 0; index < this.skeletons.length; index++) {
  6369. if (this.skeletons[index].id === id) {
  6370. return this.skeletons[index];
  6371. }
  6372. }
  6373. return null;
  6374. };
  6375. Scene.prototype.getSkeletonByName = function (name) {
  6376. for (var index = 0; index < this.skeletons.length; index++) {
  6377. if (this.skeletons[index].name === name) {
  6378. return this.skeletons[index];
  6379. }
  6380. }
  6381. return null;
  6382. };
  6383. Scene.prototype.isActiveMesh = function (mesh) {
  6384. return (this._activeMeshes.indexOf(mesh) !== -1);
  6385. };
  6386. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6387. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6388. var material = subMesh.getMaterial();
  6389. if (mesh.showSubMeshesBoundingBox) {
  6390. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6391. }
  6392. if (material) {
  6393. if (material.getRenderTargetTextures) {
  6394. if (this._processedMaterials.indexOf(material) === -1) {
  6395. this._processedMaterials.push(material);
  6396. this._renderTargets.concat(material.getRenderTargetTextures());
  6397. }
  6398. }
  6399. this._activeVertices += subMesh.verticesCount;
  6400. this._renderingManager.dispatch(subMesh);
  6401. }
  6402. }
  6403. };
  6404. Scene.prototype._evaluateActiveMeshes = function () {
  6405. this._activeMeshes.reset();
  6406. this._renderingManager.reset();
  6407. this._processedMaterials.reset();
  6408. this._activeParticleSystems.reset();
  6409. this._activeSkeletons.reset();
  6410. this._boundingBoxRenderer.reset();
  6411. if (!this._frustumPlanes) {
  6412. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6413. } else {
  6414. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6415. }
  6416. var meshes;
  6417. var len;
  6418. if (this._selectionOctree) {
  6419. var selection = this._selectionOctree.select(this._frustumPlanes);
  6420. meshes = selection.data;
  6421. len = selection.length;
  6422. } else {
  6423. len = this.meshes.length;
  6424. meshes = this.meshes;
  6425. }
  6426. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6427. var mesh = meshes[meshIndex];
  6428. this._totalVertices += mesh.getTotalVertices();
  6429. if (!mesh.isReady()) {
  6430. continue;
  6431. }
  6432. mesh.computeWorldMatrix();
  6433. mesh._preActivate();
  6434. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6435. this._meshesForIntersections.pushNoDuplicate(mesh);
  6436. }
  6437. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6438. this._activeMeshes.push(mesh);
  6439. mesh._activate(this._renderId);
  6440. this._activeMesh(mesh);
  6441. }
  6442. }
  6443. var beforeParticlesDate = new Date().getTime();
  6444. if (this.particlesEnabled) {
  6445. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6446. var particleSystem = this.particleSystems[particleIndex];
  6447. if (!particleSystem.isStarted()) {
  6448. continue;
  6449. }
  6450. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6451. this._activeParticleSystems.push(particleSystem);
  6452. particleSystem.animate();
  6453. }
  6454. }
  6455. }
  6456. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6457. };
  6458. Scene.prototype._activeMesh = function (mesh) {
  6459. if (mesh.skeleton) {
  6460. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6461. }
  6462. if (mesh.showBoundingBox) {
  6463. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6464. }
  6465. if (mesh.subMeshes) {
  6466. var len;
  6467. var subMeshes;
  6468. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6469. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6470. len = intersections.length;
  6471. subMeshes = intersections.data;
  6472. } else {
  6473. subMeshes = mesh.subMeshes;
  6474. len = subMeshes.length;
  6475. }
  6476. for (var subIndex = 0; subIndex < len; subIndex++) {
  6477. var subMesh = subMeshes[subIndex];
  6478. this._evaluateSubMesh(subMesh, mesh);
  6479. }
  6480. }
  6481. };
  6482. Scene.prototype.updateTransformMatrix = function (force) {
  6483. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6484. };
  6485. Scene.prototype._renderForCamera = function (camera) {
  6486. var engine = this._engine;
  6487. this.activeCamera = camera;
  6488. if (!this.activeCamera)
  6489. throw new Error("Active camera not set");
  6490. engine.setViewport(this.activeCamera.viewport);
  6491. this._renderId++;
  6492. this.updateTransformMatrix();
  6493. if (this.beforeCameraRender) {
  6494. this.beforeCameraRender(this.activeCamera);
  6495. }
  6496. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6497. this._evaluateActiveMeshes();
  6498. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6499. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6500. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6501. skeleton.prepare();
  6502. }
  6503. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6504. var renderTarget = this.customRenderTargets[customIndex];
  6505. this._renderTargets.push(renderTarget);
  6506. }
  6507. var beforeRenderTargetDate = new Date().getTime();
  6508. if (this.renderTargetsEnabled) {
  6509. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6510. renderTarget = this._renderTargets.data[renderIndex];
  6511. if (renderTarget._shouldRender()) {
  6512. this._renderId++;
  6513. renderTarget.render();
  6514. }
  6515. }
  6516. this._renderId++;
  6517. }
  6518. if (this._renderTargets.length > 0) {
  6519. engine.restoreDefaultFramebuffer();
  6520. }
  6521. this._renderTargetsDuration = new Date().getTime() - beforeRenderTargetDate;
  6522. this.postProcessManager._prepareFrame();
  6523. var beforeRenderDate = new Date().getTime();
  6524. if (this.layers.length) {
  6525. engine.setDepthBuffer(false);
  6526. var layerIndex;
  6527. var layer;
  6528. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6529. layer = this.layers[layerIndex];
  6530. if (layer.isBackground) {
  6531. layer.render();
  6532. }
  6533. }
  6534. engine.setDepthBuffer(true);
  6535. }
  6536. this._renderingManager.render(null, null, true, true);
  6537. this._boundingBoxRenderer.render();
  6538. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6539. this.lensFlareSystems[lensFlareSystemIndex].render();
  6540. }
  6541. if (this.layers.length) {
  6542. engine.setDepthBuffer(false);
  6543. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6544. layer = this.layers[layerIndex];
  6545. if (!layer.isBackground) {
  6546. layer.render();
  6547. }
  6548. }
  6549. engine.setDepthBuffer(true);
  6550. }
  6551. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6552. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6553. this.activeCamera._updateFromScene();
  6554. this._renderTargets.reset();
  6555. if (this.afterCameraRender) {
  6556. this.afterCameraRender(this.activeCamera);
  6557. }
  6558. };
  6559. Scene.prototype._processSubCameras = function (camera) {
  6560. if (camera.subCameras.length == 0) {
  6561. this._renderForCamera(camera);
  6562. return;
  6563. }
  6564. for (var index = 0; index < camera.subCameras.length; index++) {
  6565. this._renderForCamera(camera.subCameras[index]);
  6566. }
  6567. this.activeCamera = camera;
  6568. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6569. this.activeCamera._updateFromScene();
  6570. };
  6571. Scene.prototype._checkIntersections = function () {
  6572. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6573. var sourceMesh = this._meshesForIntersections.data[index];
  6574. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6575. var action = sourceMesh.actionManager.actions[actionIndex];
  6576. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6577. var otherMesh = action.getTriggerParameter();
  6578. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6579. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6580. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6581. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6582. sourceMesh._intersectionsInProgress.push(otherMesh);
  6583. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6584. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6585. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6586. if (indexOfOther > -1) {
  6587. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6588. }
  6589. }
  6590. }
  6591. }
  6592. }
  6593. };
  6594. Scene.prototype.render = function () {
  6595. var startDate = new Date().getTime();
  6596. this._particlesDuration = 0;
  6597. this._spritesDuration = 0;
  6598. this._activeParticles = 0;
  6599. this._renderDuration = 0;
  6600. this._evaluateActiveMeshesDuration = 0;
  6601. this._totalVertices = 0;
  6602. this._activeVertices = 0;
  6603. this._meshesForIntersections.reset();
  6604. if (this.actionManager) {
  6605. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6606. }
  6607. if (this.beforeRender) {
  6608. this.beforeRender();
  6609. }
  6610. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6611. this._onBeforeRenderCallbacks[callbackIndex]();
  6612. }
  6613. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6614. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6615. this._animate();
  6616. if (this._physicsEngine) {
  6617. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6618. }
  6619. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6620. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6621. var light = this.lights[lightIndex];
  6622. var shadowGenerator = light.getShadowGenerator();
  6623. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6624. this._renderTargets.push(shadowGenerator.getShadowMap());
  6625. }
  6626. }
  6627. this.postProcessRenderPipelineManager.update();
  6628. if (this.activeCameras.length > 0) {
  6629. var currentRenderId = this._renderId;
  6630. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6631. this._renderId = currentRenderId;
  6632. this._processSubCameras(this.activeCameras[cameraIndex]);
  6633. }
  6634. } else {
  6635. if (!this.activeCamera) {
  6636. throw new Error("No camera defined");
  6637. }
  6638. this._processSubCameras(this.activeCamera);
  6639. }
  6640. this._checkIntersections();
  6641. if (this.afterRender) {
  6642. this.afterRender();
  6643. }
  6644. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6645. this._toBeDisposed.data[index].dispose();
  6646. this._toBeDisposed[index] = null;
  6647. }
  6648. this._toBeDisposed.reset();
  6649. this._lastFrameDuration = new Date().getTime() - startDate;
  6650. };
  6651. Scene.prototype.dispose = function () {
  6652. this.beforeRender = null;
  6653. this.afterRender = null;
  6654. this.skeletons = [];
  6655. this._boundingBoxRenderer.dispose();
  6656. if (this.onDispose) {
  6657. this.onDispose();
  6658. }
  6659. this.detachControl();
  6660. var canvas = this._engine.getRenderingCanvas();
  6661. var index;
  6662. for (index = 0; index < this.cameras.length; index++) {
  6663. this.cameras[index].detachControl(canvas);
  6664. }
  6665. while (this.lights.length) {
  6666. this.lights[0].dispose();
  6667. }
  6668. while (this.meshes.length) {
  6669. this.meshes[0].dispose(true);
  6670. }
  6671. while (this.cameras.length) {
  6672. this.cameras[0].dispose();
  6673. }
  6674. while (this.materials.length) {
  6675. this.materials[0].dispose();
  6676. }
  6677. while (this.particleSystems.length) {
  6678. this.particleSystems[0].dispose();
  6679. }
  6680. while (this.spriteManagers.length) {
  6681. this.spriteManagers[0].dispose();
  6682. }
  6683. while (this.layers.length) {
  6684. this.layers[0].dispose();
  6685. }
  6686. while (this.textures.length) {
  6687. this.textures[0].dispose();
  6688. }
  6689. this.postProcessManager.dispose();
  6690. if (this._physicsEngine) {
  6691. this.disablePhysicsEngine();
  6692. }
  6693. index = this._engine.scenes.indexOf(this);
  6694. if (index > -1) {
  6695. this._engine.scenes.splice(index, 1);
  6696. }
  6697. this._engine.wipeCaches();
  6698. };
  6699. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6700. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6701. position.divideToRef(collider.radius, this._scaledPosition);
  6702. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6703. collider.retry = 0;
  6704. collider.initialVelocity = this._scaledVelocity;
  6705. collider.initialPosition = this._scaledPosition;
  6706. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6707. finalPosition.multiplyInPlace(collider.radius);
  6708. };
  6709. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6710. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6711. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6712. if (collider.retry >= maximumRetry) {
  6713. finalPosition.copyFrom(position);
  6714. return;
  6715. }
  6716. collider._initialize(position, velocity, closeDistance);
  6717. for (var index = 0; index < this.meshes.length; index++) {
  6718. var mesh = this.meshes[index];
  6719. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6720. mesh._checkCollision(collider);
  6721. }
  6722. }
  6723. if (!collider.collisionFound) {
  6724. position.addToRef(velocity, finalPosition);
  6725. return;
  6726. }
  6727. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6728. collider._getResponse(position, velocity);
  6729. }
  6730. if (velocity.length() <= closeDistance) {
  6731. finalPosition.copyFrom(position);
  6732. return;
  6733. }
  6734. collider.retry++;
  6735. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6736. };
  6737. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6738. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6739. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6740. if (!this._selectionOctree) {
  6741. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6742. }
  6743. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6744. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6745. for (var index = 0; index < this.meshes.length; index++) {
  6746. var mesh = this.meshes[index];
  6747. mesh.computeWorldMatrix(true);
  6748. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6749. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6750. BABYLON.Tools.CheckExtends(minBox, min, max);
  6751. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6752. }
  6753. this._selectionOctree.update(min, max, this.meshes);
  6754. return this._selectionOctree;
  6755. };
  6756. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6757. var engine = this._engine;
  6758. if (!camera) {
  6759. if (!this.activeCamera)
  6760. throw new Error("Active camera not set");
  6761. camera = this.activeCamera;
  6762. }
  6763. var cameraViewport = camera.viewport;
  6764. var viewport = cameraViewport.toGlobal(engine);
  6765. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6766. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6767. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6768. };
  6769. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6770. var pickingInfo = null;
  6771. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6772. var mesh = this.meshes[meshIndex];
  6773. if (predicate) {
  6774. if (!predicate(mesh)) {
  6775. continue;
  6776. }
  6777. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6778. continue;
  6779. }
  6780. var world = mesh.getWorldMatrix();
  6781. var ray = rayFunction(world);
  6782. var result = mesh.intersects(ray, fastCheck);
  6783. if (!result || !result.hit)
  6784. continue;
  6785. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6786. continue;
  6787. pickingInfo = result;
  6788. if (fastCheck) {
  6789. break;
  6790. }
  6791. }
  6792. return pickingInfo || new BABYLON.PickingInfo();
  6793. };
  6794. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6795. var _this = this;
  6796. return this._internalPick(function (world) {
  6797. return _this.createPickingRay(x, y, world, camera);
  6798. }, predicate, fastCheck);
  6799. };
  6800. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6801. var _this = this;
  6802. return this._internalPick(function (world) {
  6803. if (!_this._pickWithRayInverseMatrix) {
  6804. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6805. }
  6806. world.invertToRef(_this._pickWithRayInverseMatrix);
  6807. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6808. }, predicate, fastCheck);
  6809. };
  6810. Scene.prototype.setPointerOverMesh = function (mesh) {
  6811. if (this._pointerOverMesh === mesh) {
  6812. return;
  6813. }
  6814. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6815. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6816. }
  6817. this._pointerOverMesh = mesh;
  6818. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6819. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6820. }
  6821. };
  6822. Scene.prototype.getPointerOverMesh = function () {
  6823. return this._pointerOverMesh;
  6824. };
  6825. Scene.prototype.getPhysicsEngine = function () {
  6826. return this._physicsEngine;
  6827. };
  6828. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6829. if (this._physicsEngine) {
  6830. return true;
  6831. }
  6832. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6833. if (!this._physicsEngine.isSupported()) {
  6834. this._physicsEngine = null;
  6835. return false;
  6836. }
  6837. this._physicsEngine._initialize(gravity);
  6838. return true;
  6839. };
  6840. Scene.prototype.disablePhysicsEngine = function () {
  6841. if (!this._physicsEngine) {
  6842. return;
  6843. }
  6844. this._physicsEngine.dispose();
  6845. this._physicsEngine = undefined;
  6846. };
  6847. Scene.prototype.isPhysicsEnabled = function () {
  6848. return this._physicsEngine !== undefined;
  6849. };
  6850. Scene.prototype.setGravity = function (gravity) {
  6851. if (!this._physicsEngine) {
  6852. return;
  6853. }
  6854. this._physicsEngine._setGravity(gravity);
  6855. };
  6856. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6857. if (parts.parts) {
  6858. options = parts;
  6859. parts = parts.parts;
  6860. }
  6861. if (!this._physicsEngine) {
  6862. return null;
  6863. }
  6864. for (var index = 0; index < parts.length; index++) {
  6865. var mesh = parts[index].mesh;
  6866. mesh._physicImpostor = parts[index].impostor;
  6867. mesh._physicsMass = options.mass / parts.length;
  6868. mesh._physicsFriction = options.friction;
  6869. mesh._physicRestitution = options.restitution;
  6870. }
  6871. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6872. };
  6873. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6874. for (var index = 0; index < compound.parts.length; index++) {
  6875. var mesh = compound.parts[index].mesh;
  6876. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6877. this._physicsEngine._unregisterMesh(mesh);
  6878. }
  6879. };
  6880. Scene.prototype._getByTags = function (list, tagsQuery) {
  6881. if (tagsQuery === undefined) {
  6882. return list;
  6883. }
  6884. var listByTags = [];
  6885. for (var i in list) {
  6886. var item = list[i];
  6887. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6888. listByTags.push(item);
  6889. }
  6890. }
  6891. return listByTags;
  6892. };
  6893. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6894. return this._getByTags(this.meshes, tagsQuery);
  6895. };
  6896. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6897. return this._getByTags(this.cameras, tagsQuery);
  6898. };
  6899. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6900. return this._getByTags(this.lights, tagsQuery);
  6901. };
  6902. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6903. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6904. };
  6905. Scene.FOGMODE_NONE = 0;
  6906. Scene.FOGMODE_EXP = 1;
  6907. Scene.FOGMODE_EXP2 = 2;
  6908. Scene.FOGMODE_LINEAR = 3;
  6909. Scene.MinDeltaTime = 1.0;
  6910. Scene.MaxDeltaTime = 1000.0;
  6911. return Scene;
  6912. })();
  6913. BABYLON.Scene = Scene;
  6914. })(BABYLON || (BABYLON = {}));
  6915. var BABYLON;
  6916. (function (BABYLON) {
  6917. var VertexBuffer = (function () {
  6918. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6919. if (engine instanceof BABYLON.Mesh) {
  6920. this._engine = engine.getScene().getEngine();
  6921. } else {
  6922. this._engine = engine;
  6923. }
  6924. this._updatable = updatable;
  6925. this._data = data;
  6926. if (!postponeInternalCreation) {
  6927. this.create();
  6928. }
  6929. this._kind = kind;
  6930. switch (kind) {
  6931. case VertexBuffer.PositionKind:
  6932. this._strideSize = 3;
  6933. break;
  6934. case VertexBuffer.NormalKind:
  6935. this._strideSize = 3;
  6936. break;
  6937. case VertexBuffer.UVKind:
  6938. this._strideSize = 2;
  6939. break;
  6940. case VertexBuffer.UV2Kind:
  6941. this._strideSize = 2;
  6942. break;
  6943. case VertexBuffer.ColorKind:
  6944. this._strideSize = 3;
  6945. break;
  6946. case VertexBuffer.MatricesIndicesKind:
  6947. this._strideSize = 4;
  6948. break;
  6949. case VertexBuffer.MatricesWeightsKind:
  6950. this._strideSize = 4;
  6951. break;
  6952. }
  6953. }
  6954. VertexBuffer.prototype.isUpdatable = function () {
  6955. return this._updatable;
  6956. };
  6957. VertexBuffer.prototype.getData = function () {
  6958. return this._data;
  6959. };
  6960. VertexBuffer.prototype.getBuffer = function () {
  6961. return this._buffer;
  6962. };
  6963. VertexBuffer.prototype.getStrideSize = function () {
  6964. return this._strideSize;
  6965. };
  6966. VertexBuffer.prototype.create = function (data) {
  6967. if (!data && this._buffer) {
  6968. return;
  6969. }
  6970. data = data || this._data;
  6971. if (!this._buffer) {
  6972. if (this._updatable) {
  6973. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  6974. } else {
  6975. this._buffer = this._engine.createVertexBuffer(data);
  6976. }
  6977. }
  6978. if (this._updatable) {
  6979. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  6980. this._data = data;
  6981. }
  6982. };
  6983. VertexBuffer.prototype.update = function (data) {
  6984. this.create(data);
  6985. };
  6986. VertexBuffer.prototype.dispose = function () {
  6987. if (!this._buffer) {
  6988. return;
  6989. }
  6990. if (this._engine._releaseBuffer(this._buffer)) {
  6991. this._buffer = null;
  6992. }
  6993. };
  6994. Object.defineProperty(VertexBuffer, "PositionKind", {
  6995. get: function () {
  6996. return VertexBuffer._PositionKind;
  6997. },
  6998. enumerable: true,
  6999. configurable: true
  7000. });
  7001. Object.defineProperty(VertexBuffer, "NormalKind", {
  7002. get: function () {
  7003. return VertexBuffer._NormalKind;
  7004. },
  7005. enumerable: true,
  7006. configurable: true
  7007. });
  7008. Object.defineProperty(VertexBuffer, "UVKind", {
  7009. get: function () {
  7010. return VertexBuffer._UVKind;
  7011. },
  7012. enumerable: true,
  7013. configurable: true
  7014. });
  7015. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7016. get: function () {
  7017. return VertexBuffer._UV2Kind;
  7018. },
  7019. enumerable: true,
  7020. configurable: true
  7021. });
  7022. Object.defineProperty(VertexBuffer, "ColorKind", {
  7023. get: function () {
  7024. return VertexBuffer._ColorKind;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7030. get: function () {
  7031. return VertexBuffer._MatricesIndicesKind;
  7032. },
  7033. enumerable: true,
  7034. configurable: true
  7035. });
  7036. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7037. get: function () {
  7038. return VertexBuffer._MatricesWeightsKind;
  7039. },
  7040. enumerable: true,
  7041. configurable: true
  7042. });
  7043. VertexBuffer._PositionKind = "position";
  7044. VertexBuffer._NormalKind = "normal";
  7045. VertexBuffer._UVKind = "uv";
  7046. VertexBuffer._UV2Kind = "uv2";
  7047. VertexBuffer._ColorKind = "color";
  7048. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7049. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7050. return VertexBuffer;
  7051. })();
  7052. BABYLON.VertexBuffer = VertexBuffer;
  7053. })(BABYLON || (BABYLON = {}));
  7054. var __extends = this.__extends || function (d, b) {
  7055. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7056. function __() { this.constructor = d; }
  7057. __.prototype = b.prototype;
  7058. d.prototype = new __();
  7059. };
  7060. var BABYLON;
  7061. (function (BABYLON) {
  7062. var AbstractMesh = (function (_super) {
  7063. __extends(AbstractMesh, _super);
  7064. function AbstractMesh(name, scene) {
  7065. _super.call(this, name, scene);
  7066. this.position = new BABYLON.Vector3(0, 0, 0);
  7067. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7068. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7069. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7070. this.visibility = 1.0;
  7071. this.infiniteDistance = false;
  7072. this.isVisible = true;
  7073. this.isPickable = true;
  7074. this.showBoundingBox = false;
  7075. this.showSubMeshesBoundingBox = false;
  7076. this.onDispose = null;
  7077. this.checkCollisions = false;
  7078. this.isBlocker = false;
  7079. this.renderingGroupId = 0;
  7080. this.receiveShadows = false;
  7081. this.renderOutline = false;
  7082. this.outlineColor = BABYLON.Color3.Red();
  7083. this.outlineWidth = 0.02;
  7084. this.useOctreeForRenderingSelection = true;
  7085. this.useOctreeForPicking = true;
  7086. this.useOctreeForCollisions = true;
  7087. this.layerMask = 0xFFFFFFFF;
  7088. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7089. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7090. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7091. this._collider = new BABYLON.Collider();
  7092. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7093. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7094. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7095. this._localScaling = BABYLON.Matrix.Zero();
  7096. this._localRotation = BABYLON.Matrix.Zero();
  7097. this._localTranslation = BABYLON.Matrix.Zero();
  7098. this._localBillboard = BABYLON.Matrix.Zero();
  7099. this._localPivotScaling = BABYLON.Matrix.Zero();
  7100. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7101. this._localWorld = BABYLON.Matrix.Zero();
  7102. this._worldMatrix = BABYLON.Matrix.Zero();
  7103. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7104. this._absolutePosition = BABYLON.Vector3.Zero();
  7105. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7106. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7107. this._isDirty = false;
  7108. this._pivotMatrix = BABYLON.Matrix.Identity();
  7109. this._isDisposed = false;
  7110. this._renderId = 0;
  7111. this._intersectionsInProgress = new Array();
  7112. scene.meshes.push(this);
  7113. }
  7114. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7115. get: function () {
  7116. return AbstractMesh._BILLBOARDMODE_NONE;
  7117. },
  7118. enumerable: true,
  7119. configurable: true
  7120. });
  7121. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7122. get: function () {
  7123. return AbstractMesh._BILLBOARDMODE_X;
  7124. },
  7125. enumerable: true,
  7126. configurable: true
  7127. });
  7128. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7129. get: function () {
  7130. return AbstractMesh._BILLBOARDMODE_Y;
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7136. get: function () {
  7137. return AbstractMesh._BILLBOARDMODE_Z;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7143. get: function () {
  7144. return AbstractMesh._BILLBOARDMODE_ALL;
  7145. },
  7146. enumerable: true,
  7147. configurable: true
  7148. });
  7149. AbstractMesh.prototype.getTotalVertices = function () {
  7150. return 0;
  7151. };
  7152. AbstractMesh.prototype.getIndices = function () {
  7153. return null;
  7154. };
  7155. AbstractMesh.prototype.getVerticesData = function (kind) {
  7156. return null;
  7157. };
  7158. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7159. return false;
  7160. };
  7161. AbstractMesh.prototype.getBoundingInfo = function () {
  7162. if (!this._boundingInfo) {
  7163. this._updateBoundingInfo();
  7164. }
  7165. return this._boundingInfo;
  7166. };
  7167. AbstractMesh.prototype._preActivate = function () {
  7168. };
  7169. AbstractMesh.prototype._activate = function (renderId) {
  7170. this._renderId = renderId;
  7171. };
  7172. AbstractMesh.prototype.getWorldMatrix = function () {
  7173. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7174. this.computeWorldMatrix();
  7175. }
  7176. return this._worldMatrix;
  7177. };
  7178. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7179. get: function () {
  7180. return this._worldMatrix;
  7181. },
  7182. enumerable: true,
  7183. configurable: true
  7184. });
  7185. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7186. get: function () {
  7187. return this._absolutePosition;
  7188. },
  7189. enumerable: true,
  7190. configurable: true
  7191. });
  7192. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7193. if (!this.rotationQuaternion) {
  7194. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7195. this.rotation = BABYLON.Vector3.Zero();
  7196. }
  7197. if (!space || space == 0 /* LOCAL */) {
  7198. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7199. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7200. } else {
  7201. if (this.parent) {
  7202. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7203. invertParentWorldMatrix.invert();
  7204. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7205. }
  7206. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7207. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7208. }
  7209. };
  7210. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7211. var displacementVector = axis.scale(distance);
  7212. if (!space || space == 0 /* LOCAL */) {
  7213. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7214. this.setPositionWithLocalVector(tempV3);
  7215. } else {
  7216. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7217. }
  7218. };
  7219. AbstractMesh.prototype.getAbsolutePosition = function () {
  7220. this.computeWorldMatrix();
  7221. return this._absolutePosition;
  7222. };
  7223. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7224. if (!absolutePosition) {
  7225. return;
  7226. }
  7227. var absolutePositionX;
  7228. var absolutePositionY;
  7229. var absolutePositionZ;
  7230. if (absolutePosition.x === undefined) {
  7231. if (arguments.length < 3) {
  7232. return;
  7233. }
  7234. absolutePositionX = arguments[0];
  7235. absolutePositionY = arguments[1];
  7236. absolutePositionZ = arguments[2];
  7237. } else {
  7238. absolutePositionX = absolutePosition.x;
  7239. absolutePositionY = absolutePosition.y;
  7240. absolutePositionZ = absolutePosition.z;
  7241. }
  7242. if (this.parent) {
  7243. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7244. invertParentWorldMatrix.invert();
  7245. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7246. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7247. } else {
  7248. this.position.x = absolutePositionX;
  7249. this.position.y = absolutePositionY;
  7250. this.position.z = absolutePositionZ;
  7251. }
  7252. };
  7253. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7254. this._pivotMatrix = matrix;
  7255. this._cache.pivotMatrixUpdated = true;
  7256. };
  7257. AbstractMesh.prototype.getPivotMatrix = function () {
  7258. return this._pivotMatrix;
  7259. };
  7260. AbstractMesh.prototype._isSynchronized = function () {
  7261. if (this._isDirty) {
  7262. return false;
  7263. }
  7264. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7265. return false;
  7266. if (this._cache.pivotMatrixUpdated) {
  7267. return false;
  7268. }
  7269. if (this.infiniteDistance) {
  7270. return false;
  7271. }
  7272. if (!this._cache.position.equals(this.position))
  7273. return false;
  7274. if (this.rotationQuaternion) {
  7275. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7276. return false;
  7277. } else {
  7278. if (!this._cache.rotation.equals(this.rotation))
  7279. return false;
  7280. }
  7281. if (!this._cache.scaling.equals(this.scaling))
  7282. return false;
  7283. return true;
  7284. };
  7285. AbstractMesh.prototype._initCache = function () {
  7286. _super.prototype._initCache.call(this);
  7287. this._cache.localMatrixUpdated = false;
  7288. this._cache.position = BABYLON.Vector3.Zero();
  7289. this._cache.scaling = BABYLON.Vector3.Zero();
  7290. this._cache.rotation = BABYLON.Vector3.Zero();
  7291. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7292. };
  7293. AbstractMesh.prototype.markAsDirty = function (property) {
  7294. if (property === "rotation") {
  7295. this.rotationQuaternion = null;
  7296. }
  7297. this._currentRenderId = Number.MAX_VALUE;
  7298. this._isDirty = true;
  7299. };
  7300. AbstractMesh.prototype._updateBoundingInfo = function () {
  7301. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7302. this._boundingInfo._update(this.worldMatrixFromCache);
  7303. if (!this.subMeshes) {
  7304. return;
  7305. }
  7306. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7307. var subMesh = this.subMeshes[subIndex];
  7308. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7309. }
  7310. };
  7311. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7312. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7313. return this._worldMatrix;
  7314. }
  7315. this._cache.position.copyFrom(this.position);
  7316. this._cache.scaling.copyFrom(this.scaling);
  7317. this._cache.pivotMatrixUpdated = false;
  7318. this._currentRenderId = this.getScene().getRenderId();
  7319. this._isDirty = false;
  7320. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7321. if (this.rotationQuaternion) {
  7322. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7323. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7324. } else {
  7325. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7326. this._cache.rotation.copyFrom(this.rotation);
  7327. }
  7328. if (this.infiniteDistance && !this.parent) {
  7329. var camera = this.getScene().activeCamera;
  7330. var cameraWorldMatrix = camera.getWorldMatrix();
  7331. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7332. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7333. } else {
  7334. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7335. }
  7336. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7337. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7338. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7339. var localPosition = this.position.clone();
  7340. var zero = this.getScene().activeCamera.position.clone();
  7341. if (this.parent && this.parent.position) {
  7342. localPosition.addInPlace(this.parent.position);
  7343. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7344. }
  7345. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7346. zero = this.getScene().activeCamera.position;
  7347. } else {
  7348. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7349. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7350. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7351. zero.y = localPosition.y + 0.001;
  7352. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7353. zero.z = localPosition.z + 0.001;
  7354. }
  7355. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7356. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7357. this._localBillboard.invert();
  7358. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7359. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7360. }
  7361. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7362. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7363. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7364. } else {
  7365. this._worldMatrix.copyFrom(this._localWorld);
  7366. }
  7367. this._updateBoundingInfo();
  7368. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7369. return this._worldMatrix;
  7370. };
  7371. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7372. this.computeWorldMatrix();
  7373. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7374. };
  7375. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7376. this.computeWorldMatrix();
  7377. var invLocalWorldMatrix = this._localWorld.clone();
  7378. invLocalWorldMatrix.invert();
  7379. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7380. };
  7381. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7382. this.computeWorldMatrix();
  7383. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7384. };
  7385. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7386. yawCor = yawCor || 0;
  7387. pitchCor = pitchCor || 0;
  7388. rollCor = rollCor || 0;
  7389. var dv = targetPoint.subtract(this.position);
  7390. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7391. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7392. var pitch = Math.atan2(dv.y, len);
  7393. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7394. };
  7395. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7396. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7397. return false;
  7398. }
  7399. return true;
  7400. };
  7401. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7402. if (!this._boundingInfo || !mesh._boundingInfo) {
  7403. return false;
  7404. }
  7405. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7406. };
  7407. AbstractMesh.prototype.intersectsPoint = function (point) {
  7408. if (!this._boundingInfo) {
  7409. return false;
  7410. }
  7411. return this._boundingInfo.intersectsPoint(point);
  7412. };
  7413. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7414. var physicsEngine = this.getScene().getPhysicsEngine();
  7415. if (!physicsEngine) {
  7416. return;
  7417. }
  7418. if (impostor.impostor) {
  7419. options = impostor;
  7420. impostor = impostor.impostor;
  7421. }
  7422. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7423. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7424. physicsEngine._unregisterMesh(this);
  7425. return;
  7426. }
  7427. options.mass = options.mass || 0;
  7428. options.friction = options.friction || 0.2;
  7429. options.restitution = options.restitution || 0.9;
  7430. this._physicImpostor = impostor;
  7431. this._physicsMass = options.mass;
  7432. this._physicsFriction = options.friction;
  7433. this._physicRestitution = options.restitution;
  7434. physicsEngine._registerMesh(this, impostor, options);
  7435. };
  7436. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7437. if (!this._physicImpostor) {
  7438. return BABYLON.PhysicsEngine.NoImpostor;
  7439. }
  7440. return this._physicImpostor;
  7441. };
  7442. AbstractMesh.prototype.getPhysicsMass = function () {
  7443. if (!this._physicsMass) {
  7444. return 0;
  7445. }
  7446. return this._physicsMass;
  7447. };
  7448. AbstractMesh.prototype.getPhysicsFriction = function () {
  7449. if (!this._physicsFriction) {
  7450. return 0;
  7451. }
  7452. return this._physicsFriction;
  7453. };
  7454. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7455. if (!this._physicRestitution) {
  7456. return 0;
  7457. }
  7458. return this._physicRestitution;
  7459. };
  7460. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7461. if (!this._physicImpostor) {
  7462. return;
  7463. }
  7464. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7465. };
  7466. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7467. if (!this._physicImpostor) {
  7468. return;
  7469. }
  7470. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7471. };
  7472. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7473. if (!this._physicImpostor) {
  7474. return;
  7475. }
  7476. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7477. };
  7478. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7479. var globalPosition = this.getAbsolutePosition();
  7480. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7481. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7482. this._collider.radius = this.ellipsoid;
  7483. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7484. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7485. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7486. this.position.addInPlace(this._diffPositionForCollisions);
  7487. }
  7488. };
  7489. /**
  7490. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7491. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7492. */
  7493. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7494. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7495. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7496. if (!this._submeshesOctree) {
  7497. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7498. }
  7499. this.computeWorldMatrix(true);
  7500. var bbox = this.getBoundingInfo().boundingBox;
  7501. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7502. return this._submeshesOctree;
  7503. };
  7504. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7505. this._generatePointsArray();
  7506. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7507. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7508. subMesh._lastColliderWorldVertices = [];
  7509. subMesh._trianglePlanes = [];
  7510. var start = subMesh.verticesStart;
  7511. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7512. for (var i = start; i < end; i++) {
  7513. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7514. }
  7515. }
  7516. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7517. };
  7518. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7519. var subMeshes;
  7520. var len;
  7521. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7522. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7523. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7524. len = intersections.length;
  7525. subMeshes = intersections.data;
  7526. } else {
  7527. subMeshes = this.subMeshes;
  7528. len = subMeshes.length;
  7529. }
  7530. for (var index = 0; index < len; index++) {
  7531. var subMesh = subMeshes[index];
  7532. if (len > 1 && !subMesh._checkCollision(collider))
  7533. continue;
  7534. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7535. }
  7536. };
  7537. AbstractMesh.prototype._checkCollision = function (collider) {
  7538. if (!this._boundingInfo._checkCollision(collider))
  7539. return;
  7540. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7541. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7542. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7543. };
  7544. AbstractMesh.prototype._generatePointsArray = function () {
  7545. return false;
  7546. };
  7547. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7548. var pickingInfo = new BABYLON.PickingInfo();
  7549. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7550. return pickingInfo;
  7551. }
  7552. if (!this._generatePointsArray()) {
  7553. return pickingInfo;
  7554. }
  7555. var intersectInfo = null;
  7556. var subMeshes;
  7557. var len;
  7558. if (this._submeshesOctree && this.useOctreeForPicking) {
  7559. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7560. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7561. len = intersections.length;
  7562. subMeshes = intersections.data;
  7563. } else {
  7564. subMeshes = this.subMeshes;
  7565. len = subMeshes.length;
  7566. }
  7567. for (var index = 0; index < len; index++) {
  7568. var subMesh = subMeshes[index];
  7569. if (len > 1 && !subMesh.canIntersects(ray))
  7570. continue;
  7571. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7572. if (currentIntersectInfo) {
  7573. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7574. intersectInfo = currentIntersectInfo;
  7575. if (fastCheck) {
  7576. break;
  7577. }
  7578. }
  7579. }
  7580. }
  7581. if (intersectInfo) {
  7582. var world = this.getWorldMatrix();
  7583. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7584. var direction = ray.direction.clone();
  7585. direction.normalize();
  7586. direction = direction.scale(intersectInfo.distance);
  7587. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7588. var pickedPoint = worldOrigin.add(worldDirection);
  7589. pickingInfo.hit = true;
  7590. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7591. pickingInfo.pickedPoint = pickedPoint;
  7592. pickingInfo.pickedMesh = this;
  7593. pickingInfo.bu = intersectInfo.bu;
  7594. pickingInfo.bv = intersectInfo.bv;
  7595. pickingInfo.faceId = intersectInfo.faceId;
  7596. return pickingInfo;
  7597. }
  7598. return pickingInfo;
  7599. };
  7600. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7601. return null;
  7602. };
  7603. AbstractMesh.prototype.releaseSubMeshes = function () {
  7604. if (this.subMeshes) {
  7605. while (this.subMeshes.length) {
  7606. this.subMeshes[0].dispose();
  7607. }
  7608. } else {
  7609. this.subMeshes = new Array();
  7610. }
  7611. };
  7612. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7613. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7614. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7615. }
  7616. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7617. var other = this._intersectionsInProgress[index];
  7618. var pos = other._intersectionsInProgress.indexOf(this);
  7619. other._intersectionsInProgress.splice(pos, 1);
  7620. }
  7621. this._intersectionsInProgress = [];
  7622. this.releaseSubMeshes();
  7623. var index = this.getScene().meshes.indexOf(this);
  7624. if (index != -1) {
  7625. this.getScene().meshes.splice(index, 1);
  7626. }
  7627. if (!doNotRecurse) {
  7628. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7629. if (this.getScene().particleSystems[index].emitter == this) {
  7630. this.getScene().particleSystems[index].dispose();
  7631. index--;
  7632. }
  7633. }
  7634. var objects = this.getScene().meshes.slice(0);
  7635. for (index = 0; index < objects.length; index++) {
  7636. if (objects[index].parent == this) {
  7637. objects[index].dispose();
  7638. }
  7639. }
  7640. } else {
  7641. for (index = 0; index < this.getScene().meshes.length; index++) {
  7642. var obj = this.getScene().meshes[index];
  7643. if (obj.parent === this) {
  7644. obj.parent = null;
  7645. obj.computeWorldMatrix(true);
  7646. }
  7647. }
  7648. }
  7649. this._isDisposed = true;
  7650. if (this.onDispose) {
  7651. this.onDispose();
  7652. }
  7653. };
  7654. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7655. AbstractMesh._BILLBOARDMODE_X = 1;
  7656. AbstractMesh._BILLBOARDMODE_Y = 2;
  7657. AbstractMesh._BILLBOARDMODE_Z = 4;
  7658. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7659. return AbstractMesh;
  7660. })(BABYLON.Node);
  7661. BABYLON.AbstractMesh = AbstractMesh;
  7662. })(BABYLON || (BABYLON = {}));
  7663. var __extends = this.__extends || function (d, b) {
  7664. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7665. function __() { this.constructor = d; }
  7666. __.prototype = b.prototype;
  7667. d.prototype = new __();
  7668. };
  7669. var BABYLON;
  7670. (function (BABYLON) {
  7671. var _InstancesBatch = (function () {
  7672. function _InstancesBatch() {
  7673. this.mustReturn = false;
  7674. this.visibleInstances = new Array();
  7675. this.renderSelf = new Array();
  7676. }
  7677. return _InstancesBatch;
  7678. })();
  7679. BABYLON._InstancesBatch = _InstancesBatch;
  7680. var Mesh = (function (_super) {
  7681. __extends(Mesh, _super);
  7682. function Mesh(name, scene) {
  7683. _super.call(this, name, scene);
  7684. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7685. this.instances = new Array();
  7686. this._onBeforeRenderCallbacks = new Array();
  7687. this._onAfterRenderCallbacks = new Array();
  7688. this._visibleInstances = {};
  7689. this._renderIdForInstances = new Array();
  7690. this._batchCache = new _InstancesBatch();
  7691. this._instancesBufferSize = 32 * 16 * 4;
  7692. }
  7693. Mesh.prototype.getTotalVertices = function () {
  7694. if (!this._geometry) {
  7695. return 0;
  7696. }
  7697. return this._geometry.getTotalVertices();
  7698. };
  7699. Mesh.prototype.getVerticesData = function (kind) {
  7700. if (!this._geometry) {
  7701. return null;
  7702. }
  7703. return this._geometry.getVerticesData(kind);
  7704. };
  7705. Mesh.prototype.getVertexBuffer = function (kind) {
  7706. if (!this._geometry) {
  7707. return undefined;
  7708. }
  7709. return this._geometry.getVertexBuffer(kind);
  7710. };
  7711. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7712. if (!this._geometry) {
  7713. if (this._delayInfo) {
  7714. return this._delayInfo.indexOf(kind) !== -1;
  7715. }
  7716. return false;
  7717. }
  7718. return this._geometry.isVerticesDataPresent(kind);
  7719. };
  7720. Mesh.prototype.getVerticesDataKinds = function () {
  7721. if (!this._geometry) {
  7722. var result = [];
  7723. if (this._delayInfo) {
  7724. for (var kind in this._delayInfo) {
  7725. result.push(kind);
  7726. }
  7727. }
  7728. return result;
  7729. }
  7730. return this._geometry.getVerticesDataKinds();
  7731. };
  7732. Mesh.prototype.getTotalIndices = function () {
  7733. if (!this._geometry) {
  7734. return 0;
  7735. }
  7736. return this._geometry.getTotalIndices();
  7737. };
  7738. Mesh.prototype.getIndices = function () {
  7739. if (!this._geometry) {
  7740. return [];
  7741. }
  7742. return this._geometry.getIndices();
  7743. };
  7744. Mesh.prototype.isReady = function () {
  7745. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7746. return false;
  7747. }
  7748. return _super.prototype.isReady.call(this);
  7749. };
  7750. Mesh.prototype.isDisposed = function () {
  7751. return this._isDisposed;
  7752. };
  7753. Mesh.prototype._preActivate = function () {
  7754. var sceneRenderId = this.getScene().getRenderId();
  7755. if (this._preActivateId == sceneRenderId) {
  7756. return;
  7757. }
  7758. this._preActivateId = sceneRenderId;
  7759. this._visibleInstances = null;
  7760. };
  7761. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7762. if (!this._visibleInstances) {
  7763. this._visibleInstances = {};
  7764. this._visibleInstances.defaultRenderId = renderId;
  7765. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7766. }
  7767. if (!this._visibleInstances[renderId]) {
  7768. this._visibleInstances[renderId] = new Array();
  7769. }
  7770. this._visibleInstances[renderId].push(instance);
  7771. };
  7772. Mesh.prototype.refreshBoundingInfo = function () {
  7773. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7774. if (data) {
  7775. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7776. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7777. }
  7778. if (this.subMeshes) {
  7779. for (var index = 0; index < this.subMeshes.length; index++) {
  7780. this.subMeshes[index].refreshBoundingInfo();
  7781. }
  7782. }
  7783. this._updateBoundingInfo();
  7784. };
  7785. Mesh.prototype._createGlobalSubMesh = function () {
  7786. var totalVertices = this.getTotalVertices();
  7787. if (!totalVertices || !this.getIndices()) {
  7788. return null;
  7789. }
  7790. this.releaseSubMeshes();
  7791. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7792. };
  7793. Mesh.prototype.subdivide = function (count) {
  7794. if (count < 1) {
  7795. return;
  7796. }
  7797. var totalIndices = this.getTotalIndices();
  7798. var subdivisionSize = (totalIndices / count) | 0;
  7799. var offset = 0;
  7800. while (subdivisionSize % 3 != 0) {
  7801. subdivisionSize++;
  7802. }
  7803. this.releaseSubMeshes();
  7804. for (var index = 0; index < count; index++) {
  7805. if (offset >= totalIndices) {
  7806. break;
  7807. }
  7808. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7809. offset += subdivisionSize;
  7810. }
  7811. this.synchronizeInstances();
  7812. };
  7813. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7814. if (kind instanceof Array) {
  7815. var temp = data;
  7816. data = kind;
  7817. kind = temp;
  7818. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7819. }
  7820. if (!this._geometry) {
  7821. var vertexData = new BABYLON.VertexData();
  7822. vertexData.set(data, kind);
  7823. var scene = this.getScene();
  7824. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7825. } else {
  7826. this._geometry.setVerticesData(kind, data, updatable);
  7827. }
  7828. };
  7829. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7830. if (!this._geometry) {
  7831. return;
  7832. }
  7833. if (!makeItUnique) {
  7834. this._geometry.updateVerticesData(kind, data, updateExtends);
  7835. } else {
  7836. this.makeGeometryUnique();
  7837. this.updateVerticesData(kind, data, updateExtends, false);
  7838. }
  7839. };
  7840. Mesh.prototype.makeGeometryUnique = function () {
  7841. if (!this._geometry) {
  7842. return;
  7843. }
  7844. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7845. geometry.applyToMesh(this);
  7846. };
  7847. Mesh.prototype.setIndices = function (indices) {
  7848. if (!this._geometry) {
  7849. var vertexData = new BABYLON.VertexData();
  7850. vertexData.indices = indices;
  7851. var scene = this.getScene();
  7852. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7853. } else {
  7854. this._geometry.setIndices(indices);
  7855. }
  7856. };
  7857. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7858. var engine = this.getScene().getEngine();
  7859. var indexToBind = this._geometry.getIndexBuffer();
  7860. if (wireframe) {
  7861. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7862. }
  7863. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7864. };
  7865. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7866. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7867. return;
  7868. }
  7869. var engine = this.getScene().getEngine();
  7870. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7871. };
  7872. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7873. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7874. return;
  7875. }
  7876. var engine = this.getScene().getEngine();
  7877. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7878. };
  7879. Mesh.prototype.registerBeforeRender = function (func) {
  7880. this._onBeforeRenderCallbacks.push(func);
  7881. };
  7882. Mesh.prototype.unregisterBeforeRender = function (func) {
  7883. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7884. if (index > -1) {
  7885. this._onBeforeRenderCallbacks.splice(index, 1);
  7886. }
  7887. };
  7888. Mesh.prototype.registerAfterRender = function (func) {
  7889. this._onAfterRenderCallbacks.push(func);
  7890. };
  7891. Mesh.prototype.unregisterAfterRender = function (func) {
  7892. var index = this._onAfterRenderCallbacks.indexOf(func);
  7893. if (index > -1) {
  7894. this._onAfterRenderCallbacks.splice(index, 1);
  7895. }
  7896. };
  7897. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7898. var scene = this.getScene();
  7899. this._batchCache.mustReturn = false;
  7900. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7901. this._batchCache.visibleInstances[subMeshId] = null;
  7902. if (this._visibleInstances) {
  7903. var currentRenderId = scene.getRenderId();
  7904. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7905. var selfRenderId = this._renderId;
  7906. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7907. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7908. currentRenderId = this._visibleInstances.defaultRenderId;
  7909. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7910. }
  7911. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7912. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7913. this._batchCache.mustReturn = true;
  7914. return this._batchCache;
  7915. }
  7916. if (currentRenderId !== selfRenderId) {
  7917. this._batchCache.renderSelf[subMeshId] = false;
  7918. }
  7919. }
  7920. this._renderIdForInstances[subMeshId] = currentRenderId;
  7921. }
  7922. return this._batchCache;
  7923. };
  7924. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7925. var matricesCount = this.instances.length + 1;
  7926. var bufferSize = matricesCount * 16 * 4;
  7927. while (this._instancesBufferSize < bufferSize) {
  7928. this._instancesBufferSize *= 2;
  7929. }
  7930. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7931. if (this._worldMatricesInstancesBuffer) {
  7932. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7933. }
  7934. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7935. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7936. }
  7937. var offset = 0;
  7938. var instancesCount = 0;
  7939. var world = this.getWorldMatrix();
  7940. if (batch.renderSelf[subMesh._id]) {
  7941. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7942. offset += 16;
  7943. instancesCount++;
  7944. }
  7945. var visibleInstances = batch.visibleInstances[subMesh._id];
  7946. if (visibleInstances) {
  7947. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7948. var instance = visibleInstances[instanceIndex];
  7949. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7950. offset += 16;
  7951. instancesCount++;
  7952. }
  7953. }
  7954. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7955. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7956. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7957. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  7958. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  7959. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  7960. this._draw(subMesh, !wireFrame, instancesCount);
  7961. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  7962. };
  7963. Mesh.prototype.render = function (subMesh) {
  7964. var scene = this.getScene();
  7965. var batch = this._getInstancesRenderList(subMesh._id);
  7966. if (batch.mustReturn) {
  7967. return;
  7968. }
  7969. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7970. return;
  7971. }
  7972. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7973. this._onBeforeRenderCallbacks[callbackIndex]();
  7974. }
  7975. var engine = scene.getEngine();
  7976. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  7977. var effectiveMaterial = subMesh.getMaterial();
  7978. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  7979. return;
  7980. }
  7981. var savedDepthWrite = engine.getDepthWrite();
  7982. if (this.renderOutline) {
  7983. engine.setDepthWrite(false);
  7984. scene.getOutlineRenderer().render(subMesh, batch);
  7985. }
  7986. effectiveMaterial._preBind();
  7987. var effect = effectiveMaterial.getEffect();
  7988. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  7989. this._bind(subMesh, effect, wireFrame);
  7990. var world = this.getWorldMatrix();
  7991. effectiveMaterial.bind(world, this);
  7992. if (hardwareInstancedRendering) {
  7993. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  7994. } else {
  7995. if (batch.renderSelf[subMesh._id]) {
  7996. this._draw(subMesh, !wireFrame);
  7997. }
  7998. if (batch.visibleInstances[subMesh._id]) {
  7999. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8000. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8001. world = instance.getWorldMatrix();
  8002. effectiveMaterial.bindOnlyWorldMatrix(world);
  8003. this._draw(subMesh, !wireFrame);
  8004. }
  8005. }
  8006. }
  8007. effectiveMaterial.unbind();
  8008. if (this.renderOutline && savedDepthWrite) {
  8009. engine.setDepthWrite(true);
  8010. engine.setColorWrite(false);
  8011. scene.getOutlineRenderer().render(subMesh, batch);
  8012. engine.setColorWrite(true);
  8013. }
  8014. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8015. this._onAfterRenderCallbacks[callbackIndex]();
  8016. }
  8017. };
  8018. Mesh.prototype.getEmittedParticleSystems = function () {
  8019. var results = new Array();
  8020. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8021. var particleSystem = this.getScene().particleSystems[index];
  8022. if (particleSystem.emitter === this) {
  8023. results.push(particleSystem);
  8024. }
  8025. }
  8026. return results;
  8027. };
  8028. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8029. var results = new Array();
  8030. var descendants = this.getDescendants();
  8031. descendants.push(this);
  8032. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8033. var particleSystem = this.getScene().particleSystems[index];
  8034. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8035. results.push(particleSystem);
  8036. }
  8037. }
  8038. return results;
  8039. };
  8040. Mesh.prototype.getChildren = function () {
  8041. var results = [];
  8042. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8043. var mesh = this.getScene().meshes[index];
  8044. if (mesh.parent == this) {
  8045. results.push(mesh);
  8046. }
  8047. }
  8048. return results;
  8049. };
  8050. Mesh.prototype._checkDelayState = function () {
  8051. var _this = this;
  8052. var that = this;
  8053. var scene = this.getScene();
  8054. if (this._geometry) {
  8055. this._geometry.load(scene);
  8056. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8057. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8058. scene._addPendingData(that);
  8059. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8060. _this._delayLoadingFunction(JSON.parse(data), _this);
  8061. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8062. scene._removePendingData(_this);
  8063. }, function () {
  8064. }, scene.database);
  8065. }
  8066. };
  8067. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8068. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8069. return false;
  8070. }
  8071. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8072. return false;
  8073. }
  8074. this._checkDelayState();
  8075. return true;
  8076. };
  8077. Mesh.prototype.setMaterialByID = function (id) {
  8078. var materials = this.getScene().materials;
  8079. for (var index = 0; index < materials.length; index++) {
  8080. if (materials[index].id == id) {
  8081. this.material = materials[index];
  8082. return;
  8083. }
  8084. }
  8085. var multiMaterials = this.getScene().multiMaterials;
  8086. for (index = 0; index < multiMaterials.length; index++) {
  8087. if (multiMaterials[index].id == id) {
  8088. this.material = multiMaterials[index];
  8089. return;
  8090. }
  8091. }
  8092. };
  8093. Mesh.prototype.getAnimatables = function () {
  8094. var results = [];
  8095. if (this.material) {
  8096. results.push(this.material);
  8097. }
  8098. return results;
  8099. };
  8100. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8101. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8102. return;
  8103. }
  8104. this._resetPointsArrayCache();
  8105. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8106. var temp = [];
  8107. for (var index = 0; index < data.length; index += 3) {
  8108. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8109. }
  8110. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8111. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8112. return;
  8113. }
  8114. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8115. for (index = 0; index < data.length; index += 3) {
  8116. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8117. }
  8118. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8119. };
  8120. Mesh.prototype._resetPointsArrayCache = function () {
  8121. this._positions = null;
  8122. };
  8123. Mesh.prototype._generatePointsArray = function () {
  8124. if (this._positions)
  8125. return true;
  8126. this._positions = [];
  8127. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8128. if (!data) {
  8129. return false;
  8130. }
  8131. for (var index = 0; index < data.length; index += 3) {
  8132. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8133. }
  8134. return true;
  8135. };
  8136. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8137. var result = new BABYLON.Mesh(name, this.getScene());
  8138. this._geometry.applyToMesh(result);
  8139. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8140. result.material = this.material;
  8141. if (newParent) {
  8142. result.parent = newParent;
  8143. }
  8144. if (!doNotCloneChildren) {
  8145. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8146. var mesh = this.getScene().meshes[index];
  8147. if (mesh.parent == this) {
  8148. mesh.clone(mesh.name, result);
  8149. }
  8150. }
  8151. }
  8152. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8153. var system = this.getScene().particleSystems[index];
  8154. if (system.emitter == this) {
  8155. system.clone(system.name, result);
  8156. }
  8157. }
  8158. result.computeWorldMatrix(true);
  8159. return result;
  8160. };
  8161. Mesh.prototype.dispose = function (doNotRecurse) {
  8162. if (this._geometry) {
  8163. this._geometry.releaseForMesh(this, true);
  8164. }
  8165. if (this._worldMatricesInstancesBuffer) {
  8166. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8167. this._worldMatricesInstancesBuffer = null;
  8168. }
  8169. while (this.instances.length) {
  8170. this.instances[0].dispose();
  8171. }
  8172. _super.prototype.dispose.call(this, doNotRecurse);
  8173. };
  8174. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8175. var _this = this;
  8176. var scene = this.getScene();
  8177. var onload = function (img) {
  8178. var canvas = document.createElement("canvas");
  8179. var context = canvas.getContext("2d");
  8180. var heightMapWidth = img.width;
  8181. var heightMapHeight = img.height;
  8182. canvas.width = heightMapWidth;
  8183. canvas.height = heightMapHeight;
  8184. context.drawImage(img, 0, 0);
  8185. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8186. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8187. };
  8188. BABYLON.Tools.LoadImage(url, onload, function () {
  8189. }, scene.database);
  8190. };
  8191. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8192. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8193. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8194. return;
  8195. }
  8196. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8197. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8198. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8199. var position = BABYLON.Vector3.Zero();
  8200. var normal = BABYLON.Vector3.Zero();
  8201. var uv = BABYLON.Vector2.Zero();
  8202. for (var index = 0; index < positions.length; index += 3) {
  8203. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8204. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8205. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8206. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8207. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8208. var pos = (u + v * heightMapWidth) * 4;
  8209. var r = buffer[pos] / 255.0;
  8210. var g = buffer[pos + 1] / 255.0;
  8211. var b = buffer[pos + 2] / 255.0;
  8212. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8213. normal.normalize();
  8214. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8215. position = position.add(normal);
  8216. position.toArray(positions, index);
  8217. }
  8218. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8219. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8220. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8221. };
  8222. Mesh.prototype.convertToFlatShadedMesh = function () {
  8223. var kinds = this.getVerticesDataKinds();
  8224. var vbs = [];
  8225. var data = [];
  8226. var newdata = [];
  8227. var updatableNormals = false;
  8228. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8229. var kind = kinds[kindIndex];
  8230. var vertexBuffer = this.getVertexBuffer(kind);
  8231. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8232. updatableNormals = vertexBuffer.isUpdatable();
  8233. kinds.splice(kindIndex, 1);
  8234. kindIndex--;
  8235. continue;
  8236. }
  8237. vbs[kind] = vertexBuffer;
  8238. data[kind] = vbs[kind].getData();
  8239. newdata[kind] = [];
  8240. }
  8241. var previousSubmeshes = this.subMeshes.slice(0);
  8242. var indices = this.getIndices();
  8243. var totalIndices = this.getTotalIndices();
  8244. for (index = 0; index < totalIndices; index++) {
  8245. var vertexIndex = indices[index];
  8246. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8247. kind = kinds[kindIndex];
  8248. var stride = vbs[kind].getStrideSize();
  8249. for (var offset = 0; offset < stride; offset++) {
  8250. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8251. }
  8252. }
  8253. }
  8254. var normals = [];
  8255. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8256. for (var index = 0; index < totalIndices; index += 3) {
  8257. indices[index] = index;
  8258. indices[index + 1] = index + 1;
  8259. indices[index + 2] = index + 2;
  8260. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8261. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8262. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8263. var p1p2 = p1.subtract(p2);
  8264. var p3p2 = p3.subtract(p2);
  8265. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8266. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8267. normals.push(normal.x);
  8268. normals.push(normal.y);
  8269. normals.push(normal.z);
  8270. }
  8271. }
  8272. this.setIndices(indices);
  8273. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8274. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8275. kind = kinds[kindIndex];
  8276. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8277. }
  8278. this.releaseSubMeshes();
  8279. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8280. var previousOne = previousSubmeshes[submeshIndex];
  8281. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8282. }
  8283. this.synchronizeInstances();
  8284. };
  8285. Mesh.prototype.createInstance = function (name) {
  8286. return new BABYLON.InstancedMesh(name, this);
  8287. };
  8288. Mesh.prototype.synchronizeInstances = function () {
  8289. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8290. var instance = this.instances[instanceIndex];
  8291. instance._syncSubMeshes();
  8292. }
  8293. };
  8294. Mesh.CreateBox = function (name, size, scene, updatable) {
  8295. var box = new BABYLON.Mesh(name, scene);
  8296. var vertexData = BABYLON.VertexData.CreateBox(size);
  8297. vertexData.applyToMesh(box, updatable);
  8298. return box;
  8299. };
  8300. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8301. var sphere = new BABYLON.Mesh(name, scene);
  8302. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8303. vertexData.applyToMesh(sphere, updatable);
  8304. return sphere;
  8305. };
  8306. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8307. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8308. if (scene !== undefined) {
  8309. updatable = scene;
  8310. }
  8311. scene = subdivisions;
  8312. subdivisions = 1;
  8313. }
  8314. var cylinder = new BABYLON.Mesh(name, scene);
  8315. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8316. vertexData.applyToMesh(cylinder, updatable);
  8317. return cylinder;
  8318. };
  8319. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8320. var torus = new BABYLON.Mesh(name, scene);
  8321. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8322. vertexData.applyToMesh(torus, updatable);
  8323. return torus;
  8324. };
  8325. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8326. var torusKnot = new BABYLON.Mesh(name, scene);
  8327. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8328. vertexData.applyToMesh(torusKnot, updatable);
  8329. return torusKnot;
  8330. };
  8331. Mesh.CreateLines = function (name, points, scene, updatable) {
  8332. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8333. var vertexData = BABYLON.VertexData.CreateLines(points);
  8334. vertexData.applyToMesh(lines, updatable);
  8335. return lines;
  8336. };
  8337. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8338. var plane = new BABYLON.Mesh(name, scene);
  8339. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8340. vertexData.applyToMesh(plane, updatable);
  8341. return plane;
  8342. };
  8343. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8344. var ground = new BABYLON.GroundMesh(name, scene);
  8345. ground._setReady(false);
  8346. ground._subdivisions = subdivisions;
  8347. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8348. vertexData.applyToMesh(ground, updatable);
  8349. ground._setReady(true);
  8350. return ground;
  8351. };
  8352. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8353. var tiledGround = new BABYLON.Mesh(name, scene);
  8354. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8355. vertexData.applyToMesh(tiledGround, updatable);
  8356. return tiledGround;
  8357. };
  8358. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8359. var ground = new BABYLON.GroundMesh(name, scene);
  8360. ground._subdivisions = subdivisions;
  8361. ground._setReady(false);
  8362. var onload = function (img) {
  8363. var canvas = document.createElement("canvas");
  8364. var context = canvas.getContext("2d");
  8365. var heightMapWidth = img.width;
  8366. var heightMapHeight = img.height;
  8367. canvas.width = heightMapWidth;
  8368. canvas.height = heightMapHeight;
  8369. context.drawImage(img, 0, 0);
  8370. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8371. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8372. vertexData.applyToMesh(ground, updatable);
  8373. ground._setReady(true);
  8374. };
  8375. BABYLON.Tools.LoadImage(url, onload, function () {
  8376. }, scene.database);
  8377. return ground;
  8378. };
  8379. Mesh.MinMax = function (meshes) {
  8380. var minVector = null;
  8381. var maxVector = null;
  8382. for (var i in meshes) {
  8383. var mesh = meshes[i];
  8384. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8385. if (!minVector) {
  8386. minVector = boundingBox.minimumWorld;
  8387. maxVector = boundingBox.maximumWorld;
  8388. continue;
  8389. }
  8390. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8391. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8392. }
  8393. return {
  8394. min: minVector,
  8395. max: maxVector
  8396. };
  8397. };
  8398. Mesh.Center = function (meshesOrMinMaxVector) {
  8399. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8400. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8401. };
  8402. return Mesh;
  8403. })(BABYLON.AbstractMesh);
  8404. BABYLON.Mesh = Mesh;
  8405. })(BABYLON || (BABYLON = {}));
  8406. var __extends = this.__extends || function (d, b) {
  8407. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8408. function __() { this.constructor = d; }
  8409. __.prototype = b.prototype;
  8410. d.prototype = new __();
  8411. };
  8412. var BABYLON;
  8413. (function (BABYLON) {
  8414. var GroundMesh = (function (_super) {
  8415. __extends(GroundMesh, _super);
  8416. function GroundMesh(name, scene) {
  8417. _super.call(this, name, scene);
  8418. this.generateOctree = false;
  8419. this._worldInverse = new BABYLON.Matrix();
  8420. }
  8421. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8422. get: function () {
  8423. return this._subdivisions;
  8424. },
  8425. enumerable: true,
  8426. configurable: true
  8427. });
  8428. GroundMesh.prototype.optimize = function (chunksCount) {
  8429. this.subdivide(this._subdivisions);
  8430. this.createOrUpdateSubmeshesOctree(32);
  8431. };
  8432. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8433. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8434. this.getWorldMatrix().invertToRef(this._worldInverse);
  8435. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8436. var pickInfo = this.intersects(ray);
  8437. if (pickInfo.hit) {
  8438. return pickInfo.pickedPoint.y;
  8439. }
  8440. return 0;
  8441. };
  8442. return GroundMesh;
  8443. })(BABYLON.Mesh);
  8444. BABYLON.GroundMesh = GroundMesh;
  8445. })(BABYLON || (BABYLON = {}));
  8446. var __extends = this.__extends || function (d, b) {
  8447. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8448. function __() { this.constructor = d; }
  8449. __.prototype = b.prototype;
  8450. d.prototype = new __();
  8451. };
  8452. var BABYLON;
  8453. (function (BABYLON) {
  8454. var InstancedMesh = (function (_super) {
  8455. __extends(InstancedMesh, _super);
  8456. function InstancedMesh(name, source) {
  8457. _super.call(this, name, source.getScene());
  8458. source.instances.push(this);
  8459. this._sourceMesh = source;
  8460. this.position.copyFrom(source.position);
  8461. this.rotation.copyFrom(source.rotation);
  8462. this.scaling.copyFrom(source.scaling);
  8463. if (source.rotationQuaternion) {
  8464. this.rotationQuaternion = source.rotationQuaternion.clone();
  8465. }
  8466. this.infiniteDistance = source.infiniteDistance;
  8467. this.setPivotMatrix(source.getPivotMatrix());
  8468. this.refreshBoundingInfo();
  8469. this._syncSubMeshes();
  8470. }
  8471. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8472. get: function () {
  8473. return this._sourceMesh.receiveShadows;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(InstancedMesh.prototype, "material", {
  8479. get: function () {
  8480. return this._sourceMesh.material;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8486. get: function () {
  8487. return this._sourceMesh.visibility;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8493. get: function () {
  8494. return this._sourceMesh.skeleton;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. InstancedMesh.prototype.getTotalVertices = function () {
  8500. return this._sourceMesh.getTotalVertices();
  8501. };
  8502. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8503. get: function () {
  8504. return this._sourceMesh;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. InstancedMesh.prototype.getVerticesData = function (kind) {
  8510. return this._sourceMesh.getVerticesData(kind);
  8511. };
  8512. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8513. return this._sourceMesh.isVerticesDataPresent(kind);
  8514. };
  8515. InstancedMesh.prototype.getIndices = function () {
  8516. return this._sourceMesh.getIndices();
  8517. };
  8518. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8519. get: function () {
  8520. return this._sourceMesh._positions;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8526. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8527. if (data) {
  8528. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8529. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8530. }
  8531. this._updateBoundingInfo();
  8532. };
  8533. InstancedMesh.prototype._preActivate = function () {
  8534. this.sourceMesh._preActivate();
  8535. };
  8536. InstancedMesh.prototype._activate = function (renderId) {
  8537. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8538. };
  8539. InstancedMesh.prototype._syncSubMeshes = function () {
  8540. this.releaseSubMeshes();
  8541. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8542. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8543. }
  8544. };
  8545. InstancedMesh.prototype._generatePointsArray = function () {
  8546. return this._sourceMesh._generatePointsArray();
  8547. };
  8548. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8549. var result = this._sourceMesh.createInstance(name);
  8550. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8551. this.refreshBoundingInfo();
  8552. if (newParent) {
  8553. result.parent = newParent;
  8554. }
  8555. if (!doNotCloneChildren) {
  8556. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8557. var mesh = this.getScene().meshes[index];
  8558. if (mesh.parent == this) {
  8559. mesh.clone(mesh.name, result);
  8560. }
  8561. }
  8562. }
  8563. result.computeWorldMatrix(true);
  8564. return result;
  8565. };
  8566. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8567. var index = this._sourceMesh.instances.indexOf(this);
  8568. this._sourceMesh.instances.splice(index, 1);
  8569. _super.prototype.dispose.call(this, doNotRecurse);
  8570. };
  8571. return InstancedMesh;
  8572. })(BABYLON.AbstractMesh);
  8573. BABYLON.InstancedMesh = InstancedMesh;
  8574. })(BABYLON || (BABYLON = {}));
  8575. var BABYLON;
  8576. (function (BABYLON) {
  8577. var SubMesh = (function () {
  8578. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8579. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8580. this.materialIndex = materialIndex;
  8581. this.verticesStart = verticesStart;
  8582. this.verticesCount = verticesCount;
  8583. this.indexStart = indexStart;
  8584. this.indexCount = indexCount;
  8585. this._renderId = 0;
  8586. this._mesh = mesh;
  8587. this._renderingMesh = renderingMesh || mesh;
  8588. mesh.subMeshes.push(this);
  8589. this._id = mesh.subMeshes.length - 1;
  8590. if (createBoundingBox) {
  8591. this.refreshBoundingInfo();
  8592. }
  8593. }
  8594. SubMesh.prototype.getBoundingInfo = function () {
  8595. return this._boundingInfo;
  8596. };
  8597. SubMesh.prototype.getMesh = function () {
  8598. return this._mesh;
  8599. };
  8600. SubMesh.prototype.getRenderingMesh = function () {
  8601. return this._renderingMesh;
  8602. };
  8603. SubMesh.prototype.getMaterial = function () {
  8604. var rootMaterial = this._renderingMesh.material;
  8605. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8606. var multiMaterial = rootMaterial;
  8607. return multiMaterial.getSubMaterial(this.materialIndex);
  8608. }
  8609. if (!rootMaterial) {
  8610. return this._mesh.getScene().defaultMaterial;
  8611. }
  8612. return rootMaterial;
  8613. };
  8614. SubMesh.prototype.refreshBoundingInfo = function () {
  8615. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8616. if (!data) {
  8617. this._boundingInfo = this._mesh._boundingInfo;
  8618. return;
  8619. }
  8620. var indices = this._renderingMesh.getIndices();
  8621. var extend;
  8622. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8623. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8624. } else {
  8625. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8626. }
  8627. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8628. };
  8629. SubMesh.prototype._checkCollision = function (collider) {
  8630. return this._boundingInfo._checkCollision(collider);
  8631. };
  8632. SubMesh.prototype.updateBoundingInfo = function (world) {
  8633. if (!this._boundingInfo) {
  8634. this.refreshBoundingInfo();
  8635. }
  8636. this._boundingInfo._update(world);
  8637. };
  8638. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8639. return this._boundingInfo.isInFrustum(frustumPlanes);
  8640. };
  8641. SubMesh.prototype.render = function () {
  8642. this._renderingMesh.render(this);
  8643. };
  8644. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8645. if (!this._linesIndexBuffer) {
  8646. var linesIndices = [];
  8647. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8648. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8649. }
  8650. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8651. this.linesIndexCount = linesIndices.length;
  8652. }
  8653. return this._linesIndexBuffer;
  8654. };
  8655. SubMesh.prototype.canIntersects = function (ray) {
  8656. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8657. };
  8658. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8659. var intersectInfo = null;
  8660. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8661. var p0 = positions[indices[index]];
  8662. var p1 = positions[indices[index + 1]];
  8663. var p2 = positions[indices[index + 2]];
  8664. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8665. if (currentIntersectInfo) {
  8666. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8667. intersectInfo = currentIntersectInfo;
  8668. intersectInfo.faceId = index / 3;
  8669. if (fastCheck) {
  8670. break;
  8671. }
  8672. }
  8673. }
  8674. }
  8675. return intersectInfo;
  8676. };
  8677. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8678. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8679. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8680. return result;
  8681. };
  8682. SubMesh.prototype.dispose = function () {
  8683. if (this._linesIndexBuffer) {
  8684. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8685. this._linesIndexBuffer = null;
  8686. }
  8687. var index = this._mesh.subMeshes.indexOf(this);
  8688. this._mesh.subMeshes.splice(index, 1);
  8689. };
  8690. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8691. var minVertexIndex = Number.MAX_VALUE;
  8692. var maxVertexIndex = -Number.MAX_VALUE;
  8693. renderingMesh = renderingMesh || mesh;
  8694. var indices = renderingMesh.getIndices();
  8695. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8696. var vertexIndex = indices[index];
  8697. if (vertexIndex < minVertexIndex)
  8698. minVertexIndex = vertexIndex;
  8699. if (vertexIndex > maxVertexIndex)
  8700. maxVertexIndex = vertexIndex;
  8701. }
  8702. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8703. };
  8704. return SubMesh;
  8705. })();
  8706. BABYLON.SubMesh = SubMesh;
  8707. })(BABYLON || (BABYLON = {}));
  8708. var BABYLON;
  8709. (function (BABYLON) {
  8710. var BaseTexture = (function () {
  8711. function BaseTexture(scene) {
  8712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8713. this.hasAlpha = false;
  8714. this.getAlphaFromRGB = false;
  8715. this.level = 1;
  8716. this.isCube = false;
  8717. this.isRenderTarget = false;
  8718. this.animations = new Array();
  8719. this.coordinatesIndex = 0;
  8720. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8721. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8722. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8723. this.anisotropicFilteringLevel = 4;
  8724. this._scene = scene;
  8725. this._scene.textures.push(this);
  8726. }
  8727. BaseTexture.prototype.getScene = function () {
  8728. return this._scene;
  8729. };
  8730. BaseTexture.prototype.getTextureMatrix = function () {
  8731. return null;
  8732. };
  8733. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8734. return null;
  8735. };
  8736. BaseTexture.prototype.getInternalTexture = function () {
  8737. return this._texture;
  8738. };
  8739. BaseTexture.prototype.isReady = function () {
  8740. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8741. return true;
  8742. }
  8743. if (this._texture) {
  8744. return this._texture.isReady;
  8745. }
  8746. return false;
  8747. };
  8748. BaseTexture.prototype.getSize = function () {
  8749. if (this._texture._width) {
  8750. return { width: this._texture._width, height: this._texture._height };
  8751. }
  8752. if (this._texture._size) {
  8753. return { width: this._texture._size, height: this._texture._size };
  8754. }
  8755. return { width: 0, height: 0 };
  8756. };
  8757. BaseTexture.prototype.getBaseSize = function () {
  8758. if (!this.isReady())
  8759. return { width: 0, height: 0 };
  8760. if (this._texture._size) {
  8761. return { width: this._texture._size, height: this._texture._size };
  8762. }
  8763. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8764. };
  8765. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8766. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8767. for (var index = 0; index < texturesCache.length; index++) {
  8768. var texturesCacheEntry = texturesCache[index];
  8769. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8770. texturesCacheEntry.references++;
  8771. return texturesCacheEntry;
  8772. }
  8773. }
  8774. return null;
  8775. };
  8776. BaseTexture.prototype.delayLoad = function () {
  8777. };
  8778. BaseTexture.prototype.releaseInternalTexture = function () {
  8779. if (!this._texture) {
  8780. return;
  8781. }
  8782. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8783. this._texture.references--;
  8784. if (this._texture.references == 0) {
  8785. var index = texturesCache.indexOf(this._texture);
  8786. texturesCache.splice(index, 1);
  8787. this._scene.getEngine()._releaseTexture(this._texture);
  8788. delete this._texture;
  8789. }
  8790. };
  8791. BaseTexture.prototype.clone = function () {
  8792. return null;
  8793. };
  8794. BaseTexture.prototype.dispose = function () {
  8795. var index = this._scene.textures.indexOf(this);
  8796. if (index >= 0) {
  8797. this._scene.textures.splice(index, 1);
  8798. }
  8799. if (this._texture === undefined) {
  8800. return;
  8801. }
  8802. this.releaseInternalTexture();
  8803. if (this.onDispose) {
  8804. this.onDispose();
  8805. }
  8806. };
  8807. return BaseTexture;
  8808. })();
  8809. BABYLON.BaseTexture = BaseTexture;
  8810. })(BABYLON || (BABYLON = {}));
  8811. var BABYLON;
  8812. (function (BABYLON) {
  8813. var RenderingGroup = (function () {
  8814. function RenderingGroup(index, scene) {
  8815. this.index = index;
  8816. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8817. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8818. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8819. this._scene = scene;
  8820. }
  8821. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8822. if (customRenderFunction) {
  8823. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8824. return true;
  8825. }
  8826. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8827. return false;
  8828. }
  8829. var engine = this._scene.getEngine();
  8830. var subIndex;
  8831. var submesh;
  8832. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8833. submesh = this._opaqueSubMeshes.data[subIndex];
  8834. this._activeVertices += submesh.verticesCount;
  8835. submesh.render();
  8836. }
  8837. engine.setAlphaTesting(true);
  8838. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8839. submesh = this._alphaTestSubMeshes.data[subIndex];
  8840. this._activeVertices += submesh.verticesCount;
  8841. submesh.render();
  8842. }
  8843. engine.setAlphaTesting(false);
  8844. if (beforeTransparents) {
  8845. beforeTransparents();
  8846. }
  8847. if (this._transparentSubMeshes.length) {
  8848. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8849. submesh = this._transparentSubMeshes.data[subIndex];
  8850. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8851. }
  8852. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8853. sortedArray.sort(function (a, b) {
  8854. if (a._distanceToCamera < b._distanceToCamera) {
  8855. return 1;
  8856. }
  8857. if (a._distanceToCamera > b._distanceToCamera) {
  8858. return -1;
  8859. }
  8860. return 0;
  8861. });
  8862. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8863. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8864. submesh = sortedArray[subIndex];
  8865. this._activeVertices += submesh.verticesCount;
  8866. submesh.render();
  8867. }
  8868. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8869. }
  8870. return true;
  8871. };
  8872. RenderingGroup.prototype.prepare = function () {
  8873. this._opaqueSubMeshes.reset();
  8874. this._transparentSubMeshes.reset();
  8875. this._alphaTestSubMeshes.reset();
  8876. };
  8877. RenderingGroup.prototype.dispatch = function (subMesh) {
  8878. var material = subMesh.getMaterial();
  8879. var mesh = subMesh.getMesh();
  8880. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8881. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8882. this._transparentSubMeshes.push(subMesh);
  8883. }
  8884. } else if (material.needAlphaTesting()) {
  8885. this._alphaTestSubMeshes.push(subMesh);
  8886. } else {
  8887. this._opaqueSubMeshes.push(subMesh);
  8888. }
  8889. };
  8890. return RenderingGroup;
  8891. })();
  8892. BABYLON.RenderingGroup = RenderingGroup;
  8893. })(BABYLON || (BABYLON = {}));
  8894. var BABYLON;
  8895. (function (BABYLON) {
  8896. var RenderingManager = (function () {
  8897. function RenderingManager(scene) {
  8898. this._renderingGroups = new Array();
  8899. this._scene = scene;
  8900. }
  8901. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8902. if (this._scene._activeParticleSystems.length === 0) {
  8903. return;
  8904. }
  8905. var beforeParticlesDate = new Date().getTime();
  8906. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8907. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8908. if (particleSystem.renderingGroupId !== index) {
  8909. continue;
  8910. }
  8911. this._clearDepthBuffer();
  8912. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8913. this._scene._activeParticles += particleSystem.render();
  8914. }
  8915. }
  8916. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8917. };
  8918. RenderingManager.prototype._renderSprites = function (index) {
  8919. if (this._scene.spriteManagers.length === 0) {
  8920. return;
  8921. }
  8922. var beforeSpritessDate = new Date().getTime();
  8923. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8924. var spriteManager = this._scene.spriteManagers[id];
  8925. if (spriteManager.renderingGroupId === index) {
  8926. this._clearDepthBuffer();
  8927. spriteManager.render();
  8928. }
  8929. }
  8930. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8931. };
  8932. RenderingManager.prototype._clearDepthBuffer = function () {
  8933. if (this._depthBufferAlreadyCleaned) {
  8934. return;
  8935. }
  8936. this._scene.getEngine().clear(0, false, true);
  8937. this._depthBufferAlreadyCleaned = true;
  8938. };
  8939. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8940. var _this = this;
  8941. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8942. this._depthBufferAlreadyCleaned = false;
  8943. var renderingGroup = this._renderingGroups[index];
  8944. if (renderingGroup) {
  8945. this._clearDepthBuffer();
  8946. if (!renderingGroup.render(customRenderFunction, function () {
  8947. if (renderSprites) {
  8948. _this._renderSprites(index);
  8949. }
  8950. })) {
  8951. this._renderingGroups.splice(index, 1);
  8952. }
  8953. } else if (renderSprites) {
  8954. this._renderSprites(index);
  8955. }
  8956. if (renderParticles) {
  8957. this._renderParticles(index, activeMeshes);
  8958. }
  8959. }
  8960. };
  8961. RenderingManager.prototype.reset = function () {
  8962. for (var index in this._renderingGroups) {
  8963. var renderingGroup = this._renderingGroups[index];
  8964. renderingGroup.prepare();
  8965. }
  8966. };
  8967. RenderingManager.prototype.dispatch = function (subMesh) {
  8968. var mesh = subMesh.getMesh();
  8969. var renderingGroupId = mesh.renderingGroupId || 0;
  8970. if (!this._renderingGroups[renderingGroupId]) {
  8971. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  8972. }
  8973. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  8974. };
  8975. RenderingManager.MAX_RENDERINGGROUPS = 4;
  8976. return RenderingManager;
  8977. })();
  8978. BABYLON.RenderingManager = RenderingManager;
  8979. })(BABYLON || (BABYLON = {}));
  8980. var __extends = this.__extends || function (d, b) {
  8981. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8982. function __() { this.constructor = d; }
  8983. __.prototype = b.prototype;
  8984. d.prototype = new __();
  8985. };
  8986. var BABYLON;
  8987. (function (BABYLON) {
  8988. var Texture = (function (_super) {
  8989. __extends(Texture, _super);
  8990. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  8991. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  8992. _super.call(this, scene);
  8993. this.uOffset = 0;
  8994. this.vOffset = 0;
  8995. this.uScale = 1.0;
  8996. this.vScale = 1.0;
  8997. this.uAng = 0;
  8998. this.vAng = 0;
  8999. this.wAng = 0;
  9000. this.name = url;
  9001. this.url = url;
  9002. this._noMipmap = noMipmap;
  9003. this._invertY = invertY;
  9004. this._samplingMode = samplingMode;
  9005. if (!url) {
  9006. return;
  9007. }
  9008. this._texture = this._getFromCache(url, noMipmap);
  9009. if (!this._texture) {
  9010. if (!scene.useDelayedTextureLoading) {
  9011. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9012. } else {
  9013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9014. }
  9015. }
  9016. }
  9017. Texture.prototype.delayLoad = function () {
  9018. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9019. return;
  9020. }
  9021. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9022. this._texture = this._getFromCache(this.url, this._noMipmap);
  9023. if (!this._texture) {
  9024. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9025. }
  9026. };
  9027. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9028. x -= this.uOffset + 0.5;
  9029. y -= this.vOffset + 0.5;
  9030. z -= 0.5;
  9031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9032. t.x *= this.uScale;
  9033. t.y *= this.vScale;
  9034. t.x += 0.5;
  9035. t.y += 0.5;
  9036. t.z += 0.5;
  9037. };
  9038. Texture.prototype.getTextureMatrix = function () {
  9039. 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) {
  9040. return this._cachedTextureMatrix;
  9041. }
  9042. this._cachedUOffset = this.uOffset;
  9043. this._cachedVOffset = this.vOffset;
  9044. this._cachedUScale = this.uScale;
  9045. this._cachedVScale = this.vScale;
  9046. this._cachedUAng = this.uAng;
  9047. this._cachedVAng = this.vAng;
  9048. this._cachedWAng = this.wAng;
  9049. if (!this._cachedTextureMatrix) {
  9050. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9051. this._rowGenerationMatrix = new BABYLON.Matrix();
  9052. this._t0 = BABYLON.Vector3.Zero();
  9053. this._t1 = BABYLON.Vector3.Zero();
  9054. this._t2 = BABYLON.Vector3.Zero();
  9055. }
  9056. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9057. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9058. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9059. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9060. this._t1.subtractInPlace(this._t0);
  9061. this._t2.subtractInPlace(this._t0);
  9062. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9063. this._cachedTextureMatrix.m[0] = this._t1.x;
  9064. this._cachedTextureMatrix.m[1] = this._t1.y;
  9065. this._cachedTextureMatrix.m[2] = this._t1.z;
  9066. this._cachedTextureMatrix.m[4] = this._t2.x;
  9067. this._cachedTextureMatrix.m[5] = this._t2.y;
  9068. this._cachedTextureMatrix.m[6] = this._t2.z;
  9069. this._cachedTextureMatrix.m[8] = this._t0.x;
  9070. this._cachedTextureMatrix.m[9] = this._t0.y;
  9071. this._cachedTextureMatrix.m[10] = this._t0.z;
  9072. return this._cachedTextureMatrix;
  9073. };
  9074. Texture.prototype.getReflectionTextureMatrix = function () {
  9075. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9076. return this._cachedTextureMatrix;
  9077. }
  9078. if (!this._cachedTextureMatrix) {
  9079. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9080. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9081. }
  9082. switch (this.coordinatesMode) {
  9083. case BABYLON.Texture.SPHERICAL_MODE:
  9084. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9085. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9086. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9087. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9088. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9089. break;
  9090. case BABYLON.Texture.PLANAR_MODE:
  9091. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9092. this._cachedTextureMatrix[0] = this.uScale;
  9093. this._cachedTextureMatrix[5] = this.vScale;
  9094. this._cachedTextureMatrix[12] = this.uOffset;
  9095. this._cachedTextureMatrix[13] = this.vOffset;
  9096. break;
  9097. case BABYLON.Texture.PROJECTION_MODE:
  9098. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9099. this._projectionModeMatrix.m[0] = 0.5;
  9100. this._projectionModeMatrix.m[5] = -0.5;
  9101. this._projectionModeMatrix.m[10] = 0.0;
  9102. this._projectionModeMatrix.m[12] = 0.5;
  9103. this._projectionModeMatrix.m[13] = 0.5;
  9104. this._projectionModeMatrix.m[14] = 1.0;
  9105. this._projectionModeMatrix.m[15] = 1.0;
  9106. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9107. break;
  9108. default:
  9109. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9110. break;
  9111. }
  9112. return this._cachedTextureMatrix;
  9113. };
  9114. Texture.prototype.clone = function () {
  9115. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9116. newTexture.hasAlpha = this.hasAlpha;
  9117. newTexture.level = this.level;
  9118. newTexture.wrapU = this.wrapU;
  9119. newTexture.wrapV = this.wrapV;
  9120. newTexture.coordinatesIndex = this.coordinatesIndex;
  9121. newTexture.coordinatesMode = this.coordinatesMode;
  9122. newTexture.uOffset = this.uOffset;
  9123. newTexture.vOffset = this.vOffset;
  9124. newTexture.uScale = this.uScale;
  9125. newTexture.vScale = this.vScale;
  9126. newTexture.uAng = this.uAng;
  9127. newTexture.vAng = this.vAng;
  9128. newTexture.wAng = this.wAng;
  9129. return newTexture;
  9130. };
  9131. Texture.NEAREST_SAMPLINGMODE = 1;
  9132. Texture.BILINEAR_SAMPLINGMODE = 2;
  9133. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9134. Texture.EXPLICIT_MODE = 0;
  9135. Texture.SPHERICAL_MODE = 1;
  9136. Texture.PLANAR_MODE = 2;
  9137. Texture.CUBIC_MODE = 3;
  9138. Texture.PROJECTION_MODE = 4;
  9139. Texture.SKYBOX_MODE = 5;
  9140. Texture.CLAMP_ADDRESSMODE = 0;
  9141. Texture.WRAP_ADDRESSMODE = 1;
  9142. Texture.MIRROR_ADDRESSMODE = 2;
  9143. return Texture;
  9144. })(BABYLON.BaseTexture);
  9145. BABYLON.Texture = Texture;
  9146. })(BABYLON || (BABYLON = {}));
  9147. var __extends = this.__extends || function (d, b) {
  9148. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9149. function __() { this.constructor = d; }
  9150. __.prototype = b.prototype;
  9151. d.prototype = new __();
  9152. };
  9153. var BABYLON;
  9154. (function (BABYLON) {
  9155. var CubeTexture = (function (_super) {
  9156. __extends(CubeTexture, _super);
  9157. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9158. _super.call(this, scene);
  9159. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9160. this.name = rootUrl;
  9161. this.url = rootUrl;
  9162. this._noMipmap = noMipmap;
  9163. this.hasAlpha = false;
  9164. this._texture = this._getFromCache(rootUrl, noMipmap);
  9165. if (!extensions) {
  9166. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9167. }
  9168. this._extensions = extensions;
  9169. if (!this._texture) {
  9170. if (!scene.useDelayedTextureLoading) {
  9171. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9172. } else {
  9173. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9174. }
  9175. }
  9176. this.isCube = true;
  9177. this._textureMatrix = BABYLON.Matrix.Identity();
  9178. }
  9179. CubeTexture.prototype.clone = function () {
  9180. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9181. newTexture.level = this.level;
  9182. newTexture.wrapU = this.wrapU;
  9183. newTexture.wrapV = this.wrapV;
  9184. newTexture.coordinatesIndex = this.coordinatesIndex;
  9185. newTexture.coordinatesMode = this.coordinatesMode;
  9186. return newTexture;
  9187. };
  9188. CubeTexture.prototype.delayLoad = function () {
  9189. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9190. return;
  9191. }
  9192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9193. this._texture = this._getFromCache(this.url, this._noMipmap);
  9194. if (!this._texture) {
  9195. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9196. }
  9197. };
  9198. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9199. return this._textureMatrix;
  9200. };
  9201. return CubeTexture;
  9202. })(BABYLON.BaseTexture);
  9203. BABYLON.CubeTexture = CubeTexture;
  9204. })(BABYLON || (BABYLON = {}));
  9205. var __extends = this.__extends || function (d, b) {
  9206. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9207. function __() { this.constructor = d; }
  9208. __.prototype = b.prototype;
  9209. d.prototype = new __();
  9210. };
  9211. var BABYLON;
  9212. (function (BABYLON) {
  9213. var RenderTargetTexture = (function (_super) {
  9214. __extends(RenderTargetTexture, _super);
  9215. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9216. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9217. _super.call(this, null, scene, !generateMipMaps);
  9218. this.renderList = new Array();
  9219. this.renderParticles = true;
  9220. this.renderSprites = false;
  9221. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9222. this._currentRefreshId = -1;
  9223. this._refreshRate = 1;
  9224. this.name = name;
  9225. this.isRenderTarget = true;
  9226. this._size = size;
  9227. this._generateMipMaps = generateMipMaps;
  9228. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9229. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9230. this._renderingManager = new BABYLON.RenderingManager(scene);
  9231. }
  9232. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9233. this._currentRefreshId = -1;
  9234. };
  9235. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9236. get: function () {
  9237. return this._refreshRate;
  9238. },
  9239. set: function (value) {
  9240. this._refreshRate = value;
  9241. this.resetRefreshCounter();
  9242. },
  9243. enumerable: true,
  9244. configurable: true
  9245. });
  9246. RenderTargetTexture.prototype._shouldRender = function () {
  9247. if (this._currentRefreshId === -1) {
  9248. this._currentRefreshId = 1;
  9249. return true;
  9250. }
  9251. if (this.refreshRate == this._currentRefreshId) {
  9252. this._currentRefreshId = 1;
  9253. return true;
  9254. }
  9255. this._currentRefreshId++;
  9256. return false;
  9257. };
  9258. RenderTargetTexture.prototype.getRenderSize = function () {
  9259. return this._size;
  9260. };
  9261. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9262. this.releaseInternalTexture();
  9263. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9264. };
  9265. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9266. var scene = this.getScene();
  9267. var engine = scene.getEngine();
  9268. if (this._waitingRenderList) {
  9269. this.renderList = [];
  9270. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9271. var id = this._waitingRenderList[index];
  9272. this.renderList.push(scene.getMeshByID(id));
  9273. }
  9274. delete this._waitingRenderList;
  9275. }
  9276. if (!this.renderList) {
  9277. return;
  9278. }
  9279. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9280. engine.bindFramebuffer(this._texture);
  9281. }
  9282. engine.clear(scene.clearColor, true, true);
  9283. this._renderingManager.reset();
  9284. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9285. var mesh = this.renderList[meshIndex];
  9286. if (mesh) {
  9287. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9288. this.resetRefreshCounter();
  9289. continue;
  9290. }
  9291. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9292. mesh._activate(scene.getRenderId());
  9293. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9294. var subMesh = mesh.subMeshes[subIndex];
  9295. scene._activeVertices += subMesh.verticesCount;
  9296. this._renderingManager.dispatch(subMesh);
  9297. }
  9298. }
  9299. }
  9300. }
  9301. if (!this._doNotChangeAspectRatio) {
  9302. scene.updateTransformMatrix(true);
  9303. }
  9304. if (this.onBeforeRender) {
  9305. this.onBeforeRender();
  9306. }
  9307. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9308. if (useCameraPostProcess) {
  9309. scene.postProcessManager._finalizeFrame(false, this._texture);
  9310. }
  9311. if (this.onAfterRender) {
  9312. this.onAfterRender();
  9313. }
  9314. engine.unBindFramebuffer(this._texture);
  9315. if (!this._doNotChangeAspectRatio) {
  9316. scene.updateTransformMatrix(true);
  9317. }
  9318. };
  9319. RenderTargetTexture.prototype.clone = function () {
  9320. var textureSize = this.getSize();
  9321. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9322. newTexture.hasAlpha = this.hasAlpha;
  9323. newTexture.level = this.level;
  9324. newTexture.coordinatesMode = this.coordinatesMode;
  9325. newTexture.renderList = this.renderList.slice(0);
  9326. return newTexture;
  9327. };
  9328. return RenderTargetTexture;
  9329. })(BABYLON.Texture);
  9330. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9331. })(BABYLON || (BABYLON = {}));
  9332. var __extends = this.__extends || function (d, b) {
  9333. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9334. function __() { this.constructor = d; }
  9335. __.prototype = b.prototype;
  9336. d.prototype = new __();
  9337. };
  9338. var BABYLON;
  9339. (function (BABYLON) {
  9340. var MirrorTexture = (function (_super) {
  9341. __extends(MirrorTexture, _super);
  9342. function MirrorTexture(name, size, scene, generateMipMaps) {
  9343. var _this = this;
  9344. _super.call(this, name, size, scene, generateMipMaps, true);
  9345. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9346. this._transformMatrix = BABYLON.Matrix.Zero();
  9347. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9348. this.onBeforeRender = function () {
  9349. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9350. _this._savedViewMatrix = scene.getViewMatrix();
  9351. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9352. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9353. scene.clipPlane = _this.mirrorPlane;
  9354. scene.getEngine().cullBackFaces = false;
  9355. };
  9356. this.onAfterRender = function () {
  9357. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9358. scene.getEngine().cullBackFaces = true;
  9359. delete scene.clipPlane;
  9360. };
  9361. }
  9362. MirrorTexture.prototype.clone = function () {
  9363. var textureSize = this.getSize();
  9364. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9365. newTexture.hasAlpha = this.hasAlpha;
  9366. newTexture.level = this.level;
  9367. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9368. newTexture.renderList = this.renderList.slice(0);
  9369. return newTexture;
  9370. };
  9371. return MirrorTexture;
  9372. })(BABYLON.RenderTargetTexture);
  9373. BABYLON.MirrorTexture = MirrorTexture;
  9374. })(BABYLON || (BABYLON = {}));
  9375. var __extends = this.__extends || function (d, b) {
  9376. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9377. function __() { this.constructor = d; }
  9378. __.prototype = b.prototype;
  9379. d.prototype = new __();
  9380. };
  9381. var BABYLON;
  9382. (function (BABYLON) {
  9383. var DynamicTexture = (function (_super) {
  9384. __extends(DynamicTexture, _super);
  9385. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9386. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9387. _super.call(this, null, scene, !generateMipMaps);
  9388. this.name = name;
  9389. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9390. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9391. this._generateMipMaps = generateMipMaps;
  9392. if (options.getContext) {
  9393. this._canvas = options;
  9394. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9395. } else {
  9396. this._canvas = document.createElement("canvas");
  9397. if (options.width) {
  9398. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9399. } else {
  9400. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9401. }
  9402. }
  9403. var textureSize = this.getSize();
  9404. this._canvas.width = textureSize.width;
  9405. this._canvas.height = textureSize.height;
  9406. this._context = this._canvas.getContext("2d");
  9407. }
  9408. DynamicTexture.prototype.getContext = function () {
  9409. return this._context;
  9410. };
  9411. DynamicTexture.prototype.update = function (invertY) {
  9412. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9413. };
  9414. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9415. var size = this.getSize();
  9416. if (clearColor) {
  9417. this._context.fillStyle = clearColor;
  9418. this._context.fillRect(0, 0, size.width, size.height);
  9419. }
  9420. this._context.font = font;
  9421. if (x === null) {
  9422. var textSize = this._context.measureText(text);
  9423. x = (size.width - textSize.width) / 2;
  9424. }
  9425. this._context.fillStyle = color;
  9426. this._context.fillText(text, x, y);
  9427. this.update(invertY);
  9428. };
  9429. DynamicTexture.prototype.clone = function () {
  9430. var textureSize = this.getSize();
  9431. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9432. newTexture.hasAlpha = this.hasAlpha;
  9433. newTexture.level = this.level;
  9434. newTexture.wrapU = this.wrapU;
  9435. newTexture.wrapV = this.wrapV;
  9436. return newTexture;
  9437. };
  9438. return DynamicTexture;
  9439. })(BABYLON.Texture);
  9440. BABYLON.DynamicTexture = DynamicTexture;
  9441. })(BABYLON || (BABYLON = {}));
  9442. var __extends = this.__extends || function (d, b) {
  9443. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9444. function __() { this.constructor = d; }
  9445. __.prototype = b.prototype;
  9446. d.prototype = new __();
  9447. };
  9448. var BABYLON;
  9449. (function (BABYLON) {
  9450. var VideoTexture = (function (_super) {
  9451. __extends(VideoTexture, _super);
  9452. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9453. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9454. var _this = this;
  9455. _super.call(this, null, scene, !generateMipMaps, invertY);
  9456. this._autoLaunch = true;
  9457. this.name = name;
  9458. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9459. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9460. var requiredWidth = size.width || size;
  9461. var requiredHeight = size.height || size;
  9462. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9463. var textureSize = this.getSize();
  9464. this.video = document.createElement("video");
  9465. this.video.width = textureSize.width;
  9466. this.video.height = textureSize.height;
  9467. this.video.autoplay = false;
  9468. this.video.loop = true;
  9469. this.video.addEventListener("canplaythrough", function () {
  9470. if (_this._texture) {
  9471. _this._texture.isReady = true;
  9472. }
  9473. });
  9474. urls.forEach(function (url) {
  9475. var source = document.createElement("source");
  9476. source.src = url;
  9477. _this.video.appendChild(source);
  9478. });
  9479. this._lastUpdate = new Date().getTime();
  9480. }
  9481. VideoTexture.prototype.update = function () {
  9482. if (this._autoLaunch) {
  9483. this._autoLaunch = false;
  9484. this.video.play();
  9485. }
  9486. var now = new Date().getTime();
  9487. if (now - this._lastUpdate < 15) {
  9488. return false;
  9489. }
  9490. this._lastUpdate = now;
  9491. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9492. return true;
  9493. };
  9494. return VideoTexture;
  9495. })(BABYLON.Texture);
  9496. BABYLON.VideoTexture = VideoTexture;
  9497. })(BABYLON || (BABYLON = {}));
  9498. var BABYLON;
  9499. (function (BABYLON) {
  9500. var EffectFallbacks = (function () {
  9501. function EffectFallbacks() {
  9502. this._defines = {};
  9503. this._currentRank = 32;
  9504. this._maxRank = -1;
  9505. }
  9506. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9507. if (!this._defines[rank]) {
  9508. if (rank < this._currentRank) {
  9509. this._currentRank = rank;
  9510. }
  9511. if (rank > this._maxRank) {
  9512. this._maxRank = rank;
  9513. }
  9514. this._defines[rank] = new Array();
  9515. }
  9516. this._defines[rank].push(define);
  9517. };
  9518. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9519. get: function () {
  9520. return this._currentRank <= this._maxRank;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9526. var currentFallbacks = this._defines[this._currentRank];
  9527. for (var index = 0; index < currentFallbacks.length; index++) {
  9528. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9529. }
  9530. this._currentRank++;
  9531. return currentDefines;
  9532. };
  9533. return EffectFallbacks;
  9534. })();
  9535. BABYLON.EffectFallbacks = EffectFallbacks;
  9536. var Effect = (function () {
  9537. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9538. var _this = this;
  9539. this._isReady = false;
  9540. this._compilationError = "";
  9541. this._valueCache = [];
  9542. this._engine = engine;
  9543. this.name = baseName;
  9544. this.defines = defines;
  9545. this._uniformsNames = uniformsNames.concat(samplers);
  9546. this._samplers = samplers;
  9547. this._attributesNames = attributesNames;
  9548. this.onError = onError;
  9549. this.onCompiled = onCompiled;
  9550. var vertexSource;
  9551. var fragmentSource;
  9552. if (baseName.vertexElement) {
  9553. vertexSource = document.getElementById(baseName.vertexElement);
  9554. } else {
  9555. vertexSource = baseName.vertex || baseName;
  9556. }
  9557. if (baseName.fragmentElement) {
  9558. fragmentSource = document.getElementById(baseName.fragmentElement);
  9559. } else {
  9560. fragmentSource = baseName.fragment || baseName;
  9561. }
  9562. this._loadVertexShader(vertexSource, function (vertexCode) {
  9563. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9564. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9565. });
  9566. });
  9567. }
  9568. Effect.prototype.isReady = function () {
  9569. return this._isReady;
  9570. };
  9571. Effect.prototype.getProgram = function () {
  9572. return this._program;
  9573. };
  9574. Effect.prototype.getAttributesNames = function () {
  9575. return this._attributesNames;
  9576. };
  9577. Effect.prototype.getAttributeLocation = function (index) {
  9578. return this._attributes[index];
  9579. };
  9580. Effect.prototype.getAttributeLocationByName = function (name) {
  9581. var index = this._attributesNames.indexOf(name);
  9582. return this._attributes[index];
  9583. };
  9584. Effect.prototype.getAttributesCount = function () {
  9585. return this._attributes.length;
  9586. };
  9587. Effect.prototype.getUniformIndex = function (uniformName) {
  9588. return this._uniformsNames.indexOf(uniformName);
  9589. };
  9590. Effect.prototype.getUniform = function (uniformName) {
  9591. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9592. };
  9593. Effect.prototype.getSamplers = function () {
  9594. return this._samplers;
  9595. };
  9596. Effect.prototype.getCompilationError = function () {
  9597. return this._compilationError;
  9598. };
  9599. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9600. if (vertex instanceof HTMLElement) {
  9601. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9602. callback(vertexCode);
  9603. return;
  9604. }
  9605. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9606. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9607. return;
  9608. }
  9609. var vertexShaderUrl;
  9610. if (vertex[0] === ".") {
  9611. vertexShaderUrl = vertex;
  9612. } else {
  9613. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9614. }
  9615. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9616. };
  9617. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9618. if (fragment instanceof HTMLElement) {
  9619. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9620. callback(fragmentCode);
  9621. return;
  9622. }
  9623. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9624. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9625. return;
  9626. }
  9627. var fragmentShaderUrl;
  9628. if (fragment[0] === ".") {
  9629. fragmentShaderUrl = fragment;
  9630. } else {
  9631. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9632. }
  9633. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9634. };
  9635. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9636. try {
  9637. var engine = this._engine;
  9638. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9639. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9640. this._attributes = engine.getAttributes(this._program, attributesNames);
  9641. for (var index = 0; index < this._samplers.length; index++) {
  9642. var sampler = this.getUniform(this._samplers[index]);
  9643. if (sampler == null) {
  9644. this._samplers.splice(index, 1);
  9645. index--;
  9646. }
  9647. }
  9648. engine.bindSamplers(this);
  9649. this._isReady = true;
  9650. if (this.onCompiled) {
  9651. this.onCompiled(this);
  9652. }
  9653. } catch (e) {
  9654. if (fallbacks && fallbacks.isMoreFallbacks) {
  9655. defines = fallbacks.reduce(defines);
  9656. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9657. } else {
  9658. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9659. BABYLON.Tools.Error("Defines: " + defines);
  9660. BABYLON.Tools.Error("Error: " + e.message);
  9661. this._compilationError = e.message;
  9662. if (this.onError) {
  9663. this.onError(this, this._compilationError);
  9664. }
  9665. }
  9666. }
  9667. };
  9668. Effect.prototype._bindTexture = function (channel, texture) {
  9669. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9670. };
  9671. Effect.prototype.setTexture = function (channel, texture) {
  9672. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9673. };
  9674. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9675. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9676. };
  9677. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9678. if (!this._valueCache[uniformName]) {
  9679. this._valueCache[uniformName] = [x, y];
  9680. return;
  9681. }
  9682. this._valueCache[uniformName][0] = x;
  9683. this._valueCache[uniformName][1] = y;
  9684. };
  9685. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9686. if (!this._valueCache[uniformName]) {
  9687. this._valueCache[uniformName] = [x, y, z];
  9688. return;
  9689. }
  9690. this._valueCache[uniformName][0] = x;
  9691. this._valueCache[uniformName][1] = y;
  9692. this._valueCache[uniformName][2] = z;
  9693. };
  9694. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9695. if (!this._valueCache[uniformName]) {
  9696. this._valueCache[uniformName] = [x, y, z, w];
  9697. return;
  9698. }
  9699. this._valueCache[uniformName][0] = x;
  9700. this._valueCache[uniformName][1] = y;
  9701. this._valueCache[uniformName][2] = z;
  9702. this._valueCache[uniformName][3] = w;
  9703. };
  9704. Effect.prototype.setArray = function (uniformName, array) {
  9705. this._engine.setArray(this.getUniform(uniformName), array);
  9706. return this;
  9707. };
  9708. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9709. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9710. return this;
  9711. };
  9712. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9713. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9714. return this;
  9715. };
  9716. Effect.prototype.setFloat = function (uniformName, value) {
  9717. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9718. return this;
  9719. this._valueCache[uniformName] = value;
  9720. this._engine.setFloat(this.getUniform(uniformName), value);
  9721. return this;
  9722. };
  9723. Effect.prototype.setBool = function (uniformName, bool) {
  9724. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9725. return this;
  9726. this._valueCache[uniformName] = bool;
  9727. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9728. return this;
  9729. };
  9730. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9731. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9732. return this;
  9733. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9734. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9735. return this;
  9736. };
  9737. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9738. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9739. return this;
  9740. this._cacheFloat2(uniformName, x, y);
  9741. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9742. return this;
  9743. };
  9744. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9745. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9746. return this;
  9747. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9748. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9749. return this;
  9750. };
  9751. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9752. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9753. return this;
  9754. this._cacheFloat3(uniformName, x, y, z);
  9755. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9756. return this;
  9757. };
  9758. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9759. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9760. return this;
  9761. this._cacheFloat4(uniformName, x, y, z, w);
  9762. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9763. return this;
  9764. };
  9765. Effect.prototype.setColor3 = function (uniformName, color3) {
  9766. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9767. return this;
  9768. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9769. this._engine.setColor3(this.getUniform(uniformName), color3);
  9770. return this;
  9771. };
  9772. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9773. 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)
  9774. return this;
  9775. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9776. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9777. return this;
  9778. };
  9779. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9780. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9781. blurPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9782. colorPixelShader:"precision mediump float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9783. colorVertexShader:"precision mediump 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}",
  9784. convolutionPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9785. defaultPixelShader:"#ifdef GL_ES\nprecision mediump 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 alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\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}",
  9786. defaultVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9787. displayPassPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9788. filterPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9789. fxaaPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9790. layerPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9791. layerVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9792. legacydefaultPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9793. legacydefaultVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9794. lensFlarePixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9795. lensFlareVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9796. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9797. outlinePixelShader:"precision mediump 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}",
  9798. outlineVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9799. particlesPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9800. particlesVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9801. passPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  9802. postprocessVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9803. refractionPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9804. shadowMapPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9805. shadowMapVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9806. spritesPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9807. spritesVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9808. };
  9809. return Effect;
  9810. })();
  9811. BABYLON.Effect = Effect;
  9812. })(BABYLON || (BABYLON = {}));
  9813. var BABYLON;
  9814. (function (BABYLON) {
  9815. var Material = (function () {
  9816. function Material(name, scene, doNotAdd) {
  9817. this.name = name;
  9818. this.checkReadyOnEveryCall = true;
  9819. this.checkReadyOnlyOnce = false;
  9820. this.state = "";
  9821. this.alpha = 1.0;
  9822. this.wireframe = false;
  9823. this.backFaceCulling = true;
  9824. this._wasPreviouslyReady = false;
  9825. this.id = name;
  9826. this._scene = scene;
  9827. if (!doNotAdd) {
  9828. scene.materials.push(this);
  9829. }
  9830. }
  9831. Material.prototype.isReady = function (mesh, useInstances) {
  9832. return true;
  9833. };
  9834. Material.prototype.getEffect = function () {
  9835. return this._effect;
  9836. };
  9837. Material.prototype.getScene = function () {
  9838. return this._scene;
  9839. };
  9840. Material.prototype.needAlphaBlending = function () {
  9841. return (this.alpha < 1.0);
  9842. };
  9843. Material.prototype.needAlphaTesting = function () {
  9844. return false;
  9845. };
  9846. Material.prototype.getAlphaTestTexture = function () {
  9847. return null;
  9848. };
  9849. Material.prototype.trackCreation = function (onCompiled, onError) {
  9850. };
  9851. Material.prototype._preBind = function () {
  9852. var engine = this._scene.getEngine();
  9853. engine.enableEffect(this._effect);
  9854. engine.setState(this.backFaceCulling);
  9855. };
  9856. Material.prototype.bind = function (world, mesh) {
  9857. };
  9858. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9859. };
  9860. Material.prototype.unbind = function () {
  9861. };
  9862. Material.prototype.dispose = function (forceDisposeEffect) {
  9863. var index = this._scene.materials.indexOf(this);
  9864. this._scene.materials.splice(index, 1);
  9865. if (forceDisposeEffect && this._effect) {
  9866. this._scene.getEngine()._releaseEffect(this._effect);
  9867. this._effect = null;
  9868. }
  9869. if (this.onDispose) {
  9870. this.onDispose();
  9871. }
  9872. };
  9873. return Material;
  9874. })();
  9875. BABYLON.Material = Material;
  9876. })(BABYLON || (BABYLON = {}));
  9877. var __extends = this.__extends || function (d, b) {
  9878. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9879. function __() { this.constructor = d; }
  9880. __.prototype = b.prototype;
  9881. d.prototype = new __();
  9882. };
  9883. var BABYLON;
  9884. (function (BABYLON) {
  9885. var maxSimultaneousLights = 4;
  9886. var FresnelParameters = (function () {
  9887. function FresnelParameters() {
  9888. this.isEnabled = true;
  9889. this.leftColor = BABYLON.Color3.White();
  9890. this.rightColor = BABYLON.Color3.Black();
  9891. this.bias = 0;
  9892. this.power = 1;
  9893. }
  9894. return FresnelParameters;
  9895. })();
  9896. BABYLON.FresnelParameters = FresnelParameters;
  9897. var StandardMaterial = (function (_super) {
  9898. __extends(StandardMaterial, _super);
  9899. function StandardMaterial(name, scene) {
  9900. var _this = this;
  9901. _super.call(this, name, scene);
  9902. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9903. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9904. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9905. this.specularPower = 64;
  9906. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9907. this.useAlphaFromDiffuseTexture = false;
  9908. this._cachedDefines = null;
  9909. this._renderTargets = new BABYLON.SmartArray(16);
  9910. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9911. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9912. this._scaledDiffuse = new BABYLON.Color3();
  9913. this._scaledSpecular = new BABYLON.Color3();
  9914. this.getRenderTargetTextures = function () {
  9915. _this._renderTargets.reset();
  9916. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9917. _this._renderTargets.push(_this.reflectionTexture);
  9918. }
  9919. return _this._renderTargets;
  9920. };
  9921. }
  9922. StandardMaterial.prototype.needAlphaBlending = function () {
  9923. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  9924. };
  9925. StandardMaterial.prototype.needAlphaTesting = function () {
  9926. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9927. };
  9928. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9929. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9930. };
  9931. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9932. return this.diffuseTexture;
  9933. };
  9934. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9935. if (this.checkReadyOnlyOnce) {
  9936. if (this._wasPreviouslyReady) {
  9937. return true;
  9938. }
  9939. }
  9940. var scene = this.getScene();
  9941. if (!this.checkReadyOnEveryCall) {
  9942. if (this._renderId === scene.getRenderId()) {
  9943. return true;
  9944. }
  9945. }
  9946. var engine = scene.getEngine();
  9947. var defines = [];
  9948. var fallbacks = new BABYLON.EffectFallbacks();
  9949. if (scene.texturesEnabled) {
  9950. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  9951. if (!this.diffuseTexture.isReady()) {
  9952. return false;
  9953. } else {
  9954. defines.push("#define DIFFUSE");
  9955. }
  9956. }
  9957. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  9958. if (!this.ambientTexture.isReady()) {
  9959. return false;
  9960. } else {
  9961. defines.push("#define AMBIENT");
  9962. }
  9963. }
  9964. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  9965. if (!this.opacityTexture.isReady()) {
  9966. return false;
  9967. } else {
  9968. defines.push("#define OPACITY");
  9969. if (this.opacityTexture.getAlphaFromRGB) {
  9970. defines.push("#define OPACITYRGB");
  9971. }
  9972. }
  9973. }
  9974. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  9975. if (!this.reflectionTexture.isReady()) {
  9976. return false;
  9977. } else {
  9978. defines.push("#define REFLECTION");
  9979. fallbacks.addFallback(0, "REFLECTION");
  9980. }
  9981. }
  9982. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  9983. if (!this.emissiveTexture.isReady()) {
  9984. return false;
  9985. } else {
  9986. defines.push("#define EMISSIVE");
  9987. }
  9988. }
  9989. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  9990. if (!this.specularTexture.isReady()) {
  9991. return false;
  9992. } else {
  9993. defines.push("#define SPECULAR");
  9994. fallbacks.addFallback(0, "SPECULAR");
  9995. }
  9996. }
  9997. }
  9998. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  9999. if (!this.bumpTexture.isReady()) {
  10000. return false;
  10001. } else {
  10002. defines.push("#define BUMP");
  10003. fallbacks.addFallback(0, "BUMP");
  10004. }
  10005. }
  10006. if (scene.clipPlane) {
  10007. defines.push("#define CLIPPLANE");
  10008. }
  10009. if (engine.getAlphaTesting()) {
  10010. defines.push("#define ALPHATEST");
  10011. }
  10012. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10013. defines.push("#define ALPHAFROMDIFFUSE");
  10014. }
  10015. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10016. defines.push("#define FOG");
  10017. fallbacks.addFallback(1, "FOG");
  10018. }
  10019. var shadowsActivated = false;
  10020. var lightIndex = 0;
  10021. if (scene.lightsEnabled) {
  10022. for (var index = 0; index < scene.lights.length; index++) {
  10023. var light = scene.lights[index];
  10024. if (!light.isEnabled()) {
  10025. continue;
  10026. }
  10027. if (light._excludedMeshesIds.length > 0) {
  10028. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10029. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10030. if (excludedMesh) {
  10031. light.excludedMeshes.push(excludedMesh);
  10032. }
  10033. }
  10034. light._excludedMeshesIds = [];
  10035. }
  10036. if (light._includedOnlyMeshesIds.length > 0) {
  10037. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10038. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10039. if (includedOnlyMesh) {
  10040. light.includedOnlyMeshes.push(includedOnlyMesh);
  10041. }
  10042. }
  10043. light._includedOnlyMeshesIds = [];
  10044. }
  10045. if (!light.canAffectMesh(mesh)) {
  10046. continue;
  10047. }
  10048. defines.push("#define LIGHT" + lightIndex);
  10049. if (lightIndex > 0) {
  10050. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10051. }
  10052. var type;
  10053. if (light instanceof BABYLON.SpotLight) {
  10054. type = "#define SPOTLIGHT" + lightIndex;
  10055. } else if (light instanceof BABYLON.HemisphericLight) {
  10056. type = "#define HEMILIGHT" + lightIndex;
  10057. } else {
  10058. type = "#define POINTDIRLIGHT" + lightIndex;
  10059. }
  10060. defines.push(type);
  10061. if (lightIndex > 0) {
  10062. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10063. }
  10064. var shadowGenerator = light.getShadowGenerator();
  10065. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10066. defines.push("#define SHADOW" + lightIndex);
  10067. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10068. if (!shadowsActivated) {
  10069. defines.push("#define SHADOWS");
  10070. shadowsActivated = true;
  10071. }
  10072. if (shadowGenerator.useVarianceShadowMap) {
  10073. defines.push("#define SHADOWVSM" + lightIndex);
  10074. if (lightIndex > 0) {
  10075. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10076. }
  10077. }
  10078. if (shadowGenerator.usePoissonSampling) {
  10079. defines.push("#define SHADOWPCF" + lightIndex);
  10080. if (lightIndex > 0) {
  10081. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10082. }
  10083. }
  10084. }
  10085. lightIndex++;
  10086. if (lightIndex == maxSimultaneousLights)
  10087. break;
  10088. }
  10089. }
  10090. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10091. var fresnelRank = 1;
  10092. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10093. defines.push("#define DIFFUSEFRESNEL");
  10094. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10095. fresnelRank++;
  10096. }
  10097. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10098. defines.push("#define OPACITYFRESNEL");
  10099. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10100. fresnelRank++;
  10101. }
  10102. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10103. defines.push("#define REFLECTIONFRESNEL");
  10104. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10105. fresnelRank++;
  10106. }
  10107. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10108. defines.push("#define EMISSIVEFRESNEL");
  10109. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10110. fresnelRank++;
  10111. }
  10112. defines.push("#define FRESNEL");
  10113. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10114. }
  10115. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10116. if (mesh) {
  10117. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10118. attribs.push(BABYLON.VertexBuffer.UVKind);
  10119. defines.push("#define UV1");
  10120. }
  10121. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10122. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10123. defines.push("#define UV2");
  10124. }
  10125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10126. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10127. defines.push("#define VERTEXCOLOR");
  10128. }
  10129. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10130. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10131. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10132. defines.push("#define BONES");
  10133. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10134. defines.push("#define BONES4");
  10135. fallbacks.addFallback(0, "BONES4");
  10136. }
  10137. if (useInstances) {
  10138. defines.push("#define INSTANCES");
  10139. attribs.push("world0");
  10140. attribs.push("world1");
  10141. attribs.push("world2");
  10142. attribs.push("world3");
  10143. }
  10144. }
  10145. var join = defines.join("\n");
  10146. if (this._cachedDefines != join) {
  10147. this._cachedDefines = join;
  10148. var shaderName = "default";
  10149. if (!scene.getEngine().getCaps().standardDerivatives) {
  10150. shaderName = "legacydefault";
  10151. }
  10152. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10153. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10154. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10155. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10156. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10157. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10158. "vFogInfos", "vFogColor",
  10159. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10160. "mBones",
  10161. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10162. "darkness0", "darkness1", "darkness2", "darkness3",
  10163. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10164. ], [
  10165. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10166. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10167. ], join, fallbacks, this.onCompiled, this.onError);
  10168. }
  10169. if (!this._effect.isReady()) {
  10170. return false;
  10171. }
  10172. this._renderId = scene.getRenderId();
  10173. this._wasPreviouslyReady = true;
  10174. return true;
  10175. };
  10176. StandardMaterial.prototype.unbind = function () {
  10177. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10178. this._effect.setTexture("reflection2DSampler", null);
  10179. }
  10180. };
  10181. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10182. this._effect.setMatrix("world", world);
  10183. };
  10184. StandardMaterial.prototype.bind = function (world, mesh) {
  10185. var scene = this.getScene();
  10186. this.bindOnlyWorldMatrix(world);
  10187. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10188. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10189. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10190. }
  10191. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10192. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10193. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10194. }
  10195. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10196. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10197. }
  10198. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10199. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10200. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10201. }
  10202. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10203. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10204. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10205. }
  10206. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10207. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10208. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10209. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10210. }
  10211. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10212. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10213. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10214. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10215. }
  10216. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10217. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10218. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10219. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10220. }
  10221. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10222. if (this.reflectionTexture.isCube) {
  10223. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10224. } else {
  10225. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10226. }
  10227. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10228. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10229. }
  10230. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10231. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10232. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10233. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10234. }
  10235. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10236. this._effect.setTexture("specularSampler", this.specularTexture);
  10237. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10238. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10239. }
  10240. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10241. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10242. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10243. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10244. }
  10245. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10246. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10247. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10248. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10249. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10250. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10251. if (scene.lightsEnabled) {
  10252. var lightIndex = 0;
  10253. for (var index = 0; index < scene.lights.length; index++) {
  10254. var light = scene.lights[index];
  10255. if (!light.isEnabled()) {
  10256. continue;
  10257. }
  10258. if (!light.canAffectMesh(mesh)) {
  10259. continue;
  10260. }
  10261. if (light instanceof BABYLON.PointLight) {
  10262. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10263. } else if (light instanceof BABYLON.DirectionalLight) {
  10264. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10265. } else if (light instanceof BABYLON.SpotLight) {
  10266. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10267. } else if (light instanceof BABYLON.HemisphericLight) {
  10268. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10269. }
  10270. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10271. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10272. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10273. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10274. var shadowGenerator = light.getShadowGenerator();
  10275. if (mesh.receiveShadows && shadowGenerator) {
  10276. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10277. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10278. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10279. }
  10280. lightIndex++;
  10281. if (lightIndex == maxSimultaneousLights)
  10282. break;
  10283. }
  10284. }
  10285. if (scene.clipPlane) {
  10286. var clipPlane = scene.clipPlane;
  10287. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10288. }
  10289. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10290. this._effect.setMatrix("view", scene.getViewMatrix());
  10291. }
  10292. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10293. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10294. this._effect.setColor3("vFogColor", scene.fogColor);
  10295. }
  10296. };
  10297. StandardMaterial.prototype.getAnimatables = function () {
  10298. var results = [];
  10299. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10300. results.push(this.diffuseTexture);
  10301. }
  10302. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10303. results.push(this.ambientTexture);
  10304. }
  10305. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10306. results.push(this.opacityTexture);
  10307. }
  10308. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10309. results.push(this.reflectionTexture);
  10310. }
  10311. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10312. results.push(this.emissiveTexture);
  10313. }
  10314. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10315. results.push(this.specularTexture);
  10316. }
  10317. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10318. results.push(this.bumpTexture);
  10319. }
  10320. return results;
  10321. };
  10322. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10323. if (this.diffuseTexture) {
  10324. this.diffuseTexture.dispose();
  10325. }
  10326. if (this.ambientTexture) {
  10327. this.ambientTexture.dispose();
  10328. }
  10329. if (this.opacityTexture) {
  10330. this.opacityTexture.dispose();
  10331. }
  10332. if (this.reflectionTexture) {
  10333. this.reflectionTexture.dispose();
  10334. }
  10335. if (this.emissiveTexture) {
  10336. this.emissiveTexture.dispose();
  10337. }
  10338. if (this.specularTexture) {
  10339. this.specularTexture.dispose();
  10340. }
  10341. if (this.bumpTexture) {
  10342. this.bumpTexture.dispose();
  10343. }
  10344. _super.prototype.dispose.call(this, forceDisposeEffect);
  10345. };
  10346. StandardMaterial.prototype.clone = function (name) {
  10347. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10348. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10349. newStandardMaterial.alpha = this.alpha;
  10350. newStandardMaterial.wireframe = this.wireframe;
  10351. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10352. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10353. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10354. }
  10355. if (this.ambientTexture && this.ambientTexture.clone) {
  10356. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10357. }
  10358. if (this.opacityTexture && this.opacityTexture.clone) {
  10359. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10360. }
  10361. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10362. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10363. }
  10364. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10365. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10366. }
  10367. if (this.specularTexture && this.specularTexture.clone) {
  10368. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10369. }
  10370. if (this.bumpTexture && this.bumpTexture.clone) {
  10371. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10372. }
  10373. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10374. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10375. newStandardMaterial.specularColor = this.specularColor.clone();
  10376. newStandardMaterial.specularPower = this.specularPower;
  10377. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10378. return newStandardMaterial;
  10379. };
  10380. StandardMaterial.DiffuseTextureEnabled = true;
  10381. StandardMaterial.AmbientTextureEnabled = true;
  10382. StandardMaterial.OpacityTextureEnabled = true;
  10383. StandardMaterial.ReflectionTextureEnabled = true;
  10384. StandardMaterial.EmissiveTextureEnabled = true;
  10385. StandardMaterial.SpecularTextureEnabled = true;
  10386. StandardMaterial.BumpTextureEnabled = true;
  10387. return StandardMaterial;
  10388. })(BABYLON.Material);
  10389. BABYLON.StandardMaterial = StandardMaterial;
  10390. })(BABYLON || (BABYLON = {}));
  10391. var __extends = this.__extends || function (d, b) {
  10392. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10393. function __() { this.constructor = d; }
  10394. __.prototype = b.prototype;
  10395. d.prototype = new __();
  10396. };
  10397. var BABYLON;
  10398. (function (BABYLON) {
  10399. var MultiMaterial = (function (_super) {
  10400. __extends(MultiMaterial, _super);
  10401. function MultiMaterial(name, scene) {
  10402. _super.call(this, name, scene, true);
  10403. this.subMaterials = new Array();
  10404. scene.multiMaterials.push(this);
  10405. }
  10406. MultiMaterial.prototype.getSubMaterial = function (index) {
  10407. if (index < 0 || index >= this.subMaterials.length) {
  10408. return this.getScene().defaultMaterial;
  10409. }
  10410. return this.subMaterials[index];
  10411. };
  10412. MultiMaterial.prototype.isReady = function (mesh) {
  10413. for (var index = 0; index < this.subMaterials.length; index++) {
  10414. var subMaterial = this.subMaterials[index];
  10415. if (subMaterial) {
  10416. if (!this.subMaterials[index].isReady(mesh)) {
  10417. return false;
  10418. }
  10419. }
  10420. }
  10421. return true;
  10422. };
  10423. return MultiMaterial;
  10424. })(BABYLON.Material);
  10425. BABYLON.MultiMaterial = MultiMaterial;
  10426. })(BABYLON || (BABYLON = {}));
  10427. var BABYLON;
  10428. (function (BABYLON) {
  10429. var Database = (function () {
  10430. function Database(urlToScene, callbackManifestChecked) {
  10431. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10432. this.callbackManifestChecked = callbackManifestChecked;
  10433. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10434. this.db = null;
  10435. this.enableSceneOffline = false;
  10436. this.enableTexturesOffline = false;
  10437. this.manifestVersionFound = 0;
  10438. this.mustUpdateRessources = false;
  10439. this.hasReachedQuota = false;
  10440. this.checkManifestFile();
  10441. }
  10442. Database.prototype.checkManifestFile = function () {
  10443. var _this = this;
  10444. function noManifestFile() {
  10445. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10446. that.enableSceneOffline = false;
  10447. that.enableTexturesOffline = false;
  10448. that.callbackManifestChecked(false);
  10449. }
  10450. var that = this;
  10451. var manifestURL = this.currentSceneUrl + ".manifest";
  10452. var xhr = new XMLHttpRequest();
  10453. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10454. xhr.open("GET", manifestURLTimeStamped, true);
  10455. xhr.addEventListener("load", function () {
  10456. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10457. try {
  10458. var manifestFile = JSON.parse(xhr.response);
  10459. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10460. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10461. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10462. _this.manifestVersionFound = manifestFile.version;
  10463. }
  10464. if (_this.callbackManifestChecked) {
  10465. _this.callbackManifestChecked(true);
  10466. }
  10467. } catch (ex) {
  10468. noManifestFile();
  10469. }
  10470. } else {
  10471. noManifestFile();
  10472. }
  10473. }, false);
  10474. xhr.addEventListener("error", function (event) {
  10475. noManifestFile();
  10476. }, false);
  10477. try {
  10478. xhr.send();
  10479. } catch (ex) {
  10480. BABYLON.Tools.Error("Error on XHR send request.");
  10481. that.callbackManifestChecked(false);
  10482. }
  10483. };
  10484. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10485. var _this = this;
  10486. function handleError() {
  10487. that.isSupported = false;
  10488. if (errorCallback)
  10489. errorCallback();
  10490. }
  10491. var that = this;
  10492. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10493. this.isSupported = false;
  10494. if (errorCallback)
  10495. errorCallback();
  10496. } else {
  10497. if (!this.db) {
  10498. this.hasReachedQuota = false;
  10499. this.isSupported = true;
  10500. var request = this.idbFactory.open("babylonjs", 1);
  10501. request.onerror = function (event) {
  10502. handleError();
  10503. };
  10504. request.onblocked = function (event) {
  10505. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10506. handleError();
  10507. };
  10508. request.onsuccess = function (event) {
  10509. _this.db = request.result;
  10510. successCallback();
  10511. };
  10512. request.onupgradeneeded = function (event) {
  10513. _this.db = (event.target).result;
  10514. try {
  10515. if (event.oldVersion > 0) {
  10516. _this.db.deleteObjectStore("scenes");
  10517. _this.db.deleteObjectStore("versions");
  10518. _this.db.deleteObjectStore("textures");
  10519. }
  10520. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10521. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10522. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10523. } catch (ex) {
  10524. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10525. handleError();
  10526. }
  10527. };
  10528. } else {
  10529. if (successCallback)
  10530. successCallback();
  10531. }
  10532. }
  10533. };
  10534. Database.prototype.loadImageFromDB = function (url, image) {
  10535. var _this = this;
  10536. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10537. var saveAndLoadImage = function () {
  10538. if (!_this.hasReachedQuota && _this.db !== null) {
  10539. _this._saveImageIntoDBAsync(completeURL, image);
  10540. } else {
  10541. image.src = url;
  10542. }
  10543. };
  10544. if (!this.mustUpdateRessources) {
  10545. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10546. } else {
  10547. saveAndLoadImage();
  10548. }
  10549. };
  10550. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10551. if (this.isSupported && this.db !== null) {
  10552. var texture;
  10553. var transaction = this.db.transaction(["textures"]);
  10554. transaction.onabort = function (event) {
  10555. image.src = url;
  10556. };
  10557. transaction.oncomplete = function (event) {
  10558. var blobTextureURL;
  10559. if (texture) {
  10560. var URL = window.URL || window.webkitURL;
  10561. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10562. image.onerror = function () {
  10563. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10564. image.src = url;
  10565. };
  10566. image.src = blobTextureURL;
  10567. } else {
  10568. notInDBCallback();
  10569. }
  10570. };
  10571. var getRequest = transaction.objectStore("textures").get(url);
  10572. getRequest.onsuccess = function (event) {
  10573. texture = (event.target).result;
  10574. };
  10575. getRequest.onerror = function (event) {
  10576. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10577. image.src = url;
  10578. };
  10579. } else {
  10580. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10581. image.src = url;
  10582. }
  10583. };
  10584. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10585. var _this = this;
  10586. if (this.isSupported) {
  10587. var generateBlobUrl = function () {
  10588. var blobTextureURL;
  10589. if (blob) {
  10590. var URL = window.URL || window.webkitURL;
  10591. try {
  10592. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10593. } catch (ex) {
  10594. blobTextureURL = URL.createObjectURL(blob);
  10595. }
  10596. }
  10597. image.src = blobTextureURL;
  10598. };
  10599. if (BABYLON.Database.isUASupportingBlobStorage) {
  10600. var xhr = new XMLHttpRequest(), blob;
  10601. xhr.open("GET", url, true);
  10602. xhr.responseType = "blob";
  10603. xhr.addEventListener("load", function () {
  10604. if (xhr.status === 200) {
  10605. blob = xhr.response;
  10606. var transaction = _this.db.transaction(["textures"], "readwrite");
  10607. transaction.onabort = function (event) {
  10608. try {
  10609. if (event.srcElement.error.name === "QuotaExceededError") {
  10610. this.hasReachedQuota = true;
  10611. }
  10612. } catch (ex) {
  10613. }
  10614. generateBlobUrl();
  10615. };
  10616. transaction.oncomplete = function (event) {
  10617. generateBlobUrl();
  10618. };
  10619. var newTexture = { textureUrl: url, data: blob };
  10620. try {
  10621. var addRequest = transaction.objectStore("textures").put(newTexture);
  10622. addRequest.onsuccess = function (event) {
  10623. };
  10624. addRequest.onerror = function (event) {
  10625. generateBlobUrl();
  10626. };
  10627. } catch (ex) {
  10628. if (ex.code === 25) {
  10629. BABYLON.Database.isUASupportingBlobStorage = false;
  10630. }
  10631. image.src = url;
  10632. }
  10633. } else {
  10634. image.src = url;
  10635. }
  10636. }, false);
  10637. xhr.addEventListener("error", function (event) {
  10638. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10639. image.src = url;
  10640. }, false);
  10641. xhr.send();
  10642. } else {
  10643. image.src = url;
  10644. }
  10645. } else {
  10646. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10647. image.src = url;
  10648. }
  10649. };
  10650. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10651. var _this = this;
  10652. var updateVersion = function (event) {
  10653. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10654. };
  10655. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10656. };
  10657. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10658. var _this = this;
  10659. if (this.isSupported) {
  10660. var version;
  10661. try {
  10662. var transaction = this.db.transaction(["versions"]);
  10663. transaction.oncomplete = function (event) {
  10664. if (version) {
  10665. if (_this.manifestVersionFound > version.data) {
  10666. _this.mustUpdateRessources = true;
  10667. updateInDBCallback();
  10668. } else {
  10669. callback(version.data);
  10670. }
  10671. } else {
  10672. _this.mustUpdateRessources = true;
  10673. updateInDBCallback();
  10674. }
  10675. };
  10676. transaction.onabort = function (event) {
  10677. callback(-1);
  10678. };
  10679. var getRequest = transaction.objectStore("versions").get(url);
  10680. getRequest.onsuccess = function (event) {
  10681. version = (event.target).result;
  10682. };
  10683. getRequest.onerror = function (event) {
  10684. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10685. callback(-1);
  10686. };
  10687. } catch (ex) {
  10688. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10689. callback(-1);
  10690. }
  10691. } else {
  10692. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10693. callback(-1);
  10694. }
  10695. };
  10696. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10697. var _this = this;
  10698. if (this.isSupported && !this.hasReachedQuota) {
  10699. try {
  10700. var transaction = this.db.transaction(["versions"], "readwrite");
  10701. transaction.onabort = function (event) {
  10702. try {
  10703. if (event.srcElement.error.name === "QuotaExceededError") {
  10704. _this.hasReachedQuota = true;
  10705. }
  10706. } catch (ex) {
  10707. }
  10708. callback(-1);
  10709. };
  10710. transaction.oncomplete = function (event) {
  10711. callback(_this.manifestVersionFound);
  10712. };
  10713. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10714. var addRequest = transaction.objectStore("versions").put(newVersion);
  10715. addRequest.onsuccess = function (event) {
  10716. };
  10717. addRequest.onerror = function (event) {
  10718. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10719. };
  10720. } catch (ex) {
  10721. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10722. callback(-1);
  10723. }
  10724. } else {
  10725. callback(-1);
  10726. }
  10727. };
  10728. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10729. var _this = this;
  10730. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10731. var saveAndLoadFile = function (event) {
  10732. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10733. };
  10734. this._checkVersionFromDB(completeUrl, function (version) {
  10735. if (version !== -1) {
  10736. if (!_this.mustUpdateRessources) {
  10737. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10738. } else {
  10739. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10740. }
  10741. } else {
  10742. errorCallback();
  10743. }
  10744. });
  10745. };
  10746. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10747. if (this.isSupported) {
  10748. var targetStore;
  10749. if (url.indexOf(".babylon") !== -1) {
  10750. targetStore = "scenes";
  10751. } else {
  10752. targetStore = "textures";
  10753. }
  10754. var file;
  10755. var transaction = this.db.transaction([targetStore]);
  10756. transaction.oncomplete = function (event) {
  10757. if (file) {
  10758. callback(file.data);
  10759. } else {
  10760. notInDBCallback();
  10761. }
  10762. };
  10763. transaction.onabort = function (event) {
  10764. notInDBCallback();
  10765. };
  10766. var getRequest = transaction.objectStore(targetStore).get(url);
  10767. getRequest.onsuccess = function (event) {
  10768. file = (event.target).result;
  10769. };
  10770. getRequest.onerror = function (event) {
  10771. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10772. notInDBCallback();
  10773. };
  10774. } else {
  10775. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10776. callback();
  10777. }
  10778. };
  10779. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10780. var _this = this;
  10781. if (this.isSupported) {
  10782. var targetStore;
  10783. if (url.indexOf(".babylon") !== -1) {
  10784. targetStore = "scenes";
  10785. } else {
  10786. targetStore = "textures";
  10787. }
  10788. var xhr = new XMLHttpRequest(), fileData;
  10789. xhr.open("GET", url, true);
  10790. if (useArrayBuffer) {
  10791. xhr.responseType = "arraybuffer";
  10792. }
  10793. xhr.onprogress = progressCallback;
  10794. xhr.addEventListener("load", function () {
  10795. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10796. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10797. if (!_this.hasReachedQuota) {
  10798. var transaction = _this.db.transaction([targetStore], "readwrite");
  10799. transaction.onabort = function (event) {
  10800. try {
  10801. if (event.srcElement.error.name === "QuotaExceededError") {
  10802. this.hasReachedQuota = true;
  10803. }
  10804. } catch (ex) {
  10805. }
  10806. callback(fileData);
  10807. };
  10808. transaction.oncomplete = function (event) {
  10809. callback(fileData);
  10810. };
  10811. var newFile;
  10812. if (targetStore === "scenes") {
  10813. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10814. } else {
  10815. newFile = { textureUrl: url, data: fileData };
  10816. }
  10817. try {
  10818. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10819. addRequest.onsuccess = function (event) {
  10820. };
  10821. addRequest.onerror = function (event) {
  10822. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10823. };
  10824. } catch (ex) {
  10825. callback(fileData);
  10826. }
  10827. } else {
  10828. callback(fileData);
  10829. }
  10830. } else {
  10831. callback();
  10832. }
  10833. }, false);
  10834. xhr.addEventListener("error", function (event) {
  10835. BABYLON.Tools.Error("error on XHR request.");
  10836. callback();
  10837. }, false);
  10838. xhr.send();
  10839. } else {
  10840. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10841. callback();
  10842. }
  10843. };
  10844. Database.isUASupportingBlobStorage = true;
  10845. Database.parseURL = function (url) {
  10846. var a = document.createElement('a');
  10847. a.href = url;
  10848. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10849. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10850. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10851. return absLocation;
  10852. };
  10853. Database.ReturnFullUrlLocation = function (url) {
  10854. if (url.indexOf("http:/") === -1) {
  10855. return (BABYLON.Database.parseURL(window.location.href) + url);
  10856. } else {
  10857. return url;
  10858. }
  10859. };
  10860. return Database;
  10861. })();
  10862. BABYLON.Database = Database;
  10863. })(BABYLON || (BABYLON = {}));
  10864. var BABYLON;
  10865. (function (BABYLON) {
  10866. var SpriteManager = (function () {
  10867. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10868. this.name = name;
  10869. this.cellSize = cellSize;
  10870. this.sprites = new Array();
  10871. this.renderingGroupId = 0;
  10872. this._vertexDeclaration = [3, 4, 4, 4];
  10873. this._vertexStrideSize = 15 * 4;
  10874. this._capacity = capacity;
  10875. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10876. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10877. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10878. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10879. this._scene = scene;
  10880. this._scene.spriteManagers.push(this);
  10881. this._vertexDeclaration = [3, 4, 4, 4];
  10882. this._vertexStrideSize = 15 * 4;
  10883. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10884. var indices = [];
  10885. var index = 0;
  10886. for (var count = 0; count < capacity; count++) {
  10887. indices.push(index);
  10888. indices.push(index + 1);
  10889. indices.push(index + 2);
  10890. indices.push(index);
  10891. indices.push(index + 2);
  10892. indices.push(index + 3);
  10893. index += 4;
  10894. }
  10895. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10896. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10897. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10898. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10899. }
  10900. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10901. var arrayOffset = index * 15;
  10902. if (offsetX == 0)
  10903. offsetX = this._epsilon;
  10904. else if (offsetX == 1)
  10905. offsetX = 1 - this._epsilon;
  10906. if (offsetY == 0)
  10907. offsetY = this._epsilon;
  10908. else if (offsetY == 1)
  10909. offsetY = 1 - this._epsilon;
  10910. this._vertices[arrayOffset] = sprite.position.x;
  10911. this._vertices[arrayOffset + 1] = sprite.position.y;
  10912. this._vertices[arrayOffset + 2] = sprite.position.z;
  10913. this._vertices[arrayOffset + 3] = sprite.angle;
  10914. this._vertices[arrayOffset + 4] = sprite.size;
  10915. this._vertices[arrayOffset + 5] = offsetX;
  10916. this._vertices[arrayOffset + 6] = offsetY;
  10917. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10918. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10919. var offset = (sprite.cellIndex / rowSize) >> 0;
  10920. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10921. this._vertices[arrayOffset + 10] = offset;
  10922. this._vertices[arrayOffset + 11] = sprite.color.r;
  10923. this._vertices[arrayOffset + 12] = sprite.color.g;
  10924. this._vertices[arrayOffset + 13] = sprite.color.b;
  10925. this._vertices[arrayOffset + 14] = sprite.color.a;
  10926. };
  10927. SpriteManager.prototype.render = function () {
  10928. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10929. return;
  10930. var engine = this._scene.getEngine();
  10931. var baseSize = this._spriteTexture.getBaseSize();
  10932. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10933. var max = Math.min(this._capacity, this.sprites.length);
  10934. var rowSize = baseSize.width / this.cellSize;
  10935. var offset = 0;
  10936. for (var index = 0; index < max; index++) {
  10937. var sprite = this.sprites[index];
  10938. if (!sprite) {
  10939. continue;
  10940. }
  10941. sprite._animate(deltaTime);
  10942. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  10943. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  10944. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  10945. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  10946. }
  10947. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  10948. var effect = this._effectBase;
  10949. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10950. effect = this._effectFog;
  10951. }
  10952. engine.enableEffect(effect);
  10953. var viewMatrix = this._scene.getViewMatrix();
  10954. effect.setTexture("diffuseSampler", this._spriteTexture);
  10955. effect.setMatrix("view", viewMatrix);
  10956. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  10957. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  10958. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10959. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  10960. effect.setColor3("vFogColor", this._scene.fogColor);
  10961. }
  10962. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  10963. effect.setBool("alphaTest", true);
  10964. engine.setColorWrite(false);
  10965. engine.draw(true, 0, max * 6);
  10966. engine.setColorWrite(true);
  10967. effect.setBool("alphaTest", false);
  10968. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10969. engine.draw(true, 0, max * 6);
  10970. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10971. };
  10972. SpriteManager.prototype.dispose = function () {
  10973. if (this._vertexBuffer) {
  10974. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  10975. this._vertexBuffer = null;
  10976. }
  10977. if (this._indexBuffer) {
  10978. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  10979. this._indexBuffer = null;
  10980. }
  10981. if (this._spriteTexture) {
  10982. this._spriteTexture.dispose();
  10983. this._spriteTexture = null;
  10984. }
  10985. var index = this._scene.spriteManagers.indexOf(this);
  10986. this._scene.spriteManagers.splice(index, 1);
  10987. if (this.onDispose) {
  10988. this.onDispose();
  10989. }
  10990. };
  10991. return SpriteManager;
  10992. })();
  10993. BABYLON.SpriteManager = SpriteManager;
  10994. })(BABYLON || (BABYLON = {}));
  10995. var BABYLON;
  10996. (function (BABYLON) {
  10997. var Sprite = (function () {
  10998. function Sprite(name, manager) {
  10999. this.name = name;
  11000. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11001. this.size = 1.0;
  11002. this.angle = 0;
  11003. this.cellIndex = 0;
  11004. this.invertU = 0;
  11005. this.invertV = 0;
  11006. this.animations = new Array();
  11007. this._animationStarted = false;
  11008. this._loopAnimation = false;
  11009. this._fromIndex = 0;
  11010. this._toIndex = 0;
  11011. this._delay = 0;
  11012. this._direction = 1;
  11013. this._frameCount = 0;
  11014. this._time = 0;
  11015. this._manager = manager;
  11016. this._manager.sprites.push(this);
  11017. this.position = BABYLON.Vector3.Zero();
  11018. }
  11019. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11020. this._fromIndex = from;
  11021. this._toIndex = to;
  11022. this._loopAnimation = loop;
  11023. this._delay = delay;
  11024. this._animationStarted = true;
  11025. this._direction = from < to ? 1 : -1;
  11026. this.cellIndex = from;
  11027. this._time = 0;
  11028. };
  11029. Sprite.prototype.stopAnimation = function () {
  11030. this._animationStarted = false;
  11031. };
  11032. Sprite.prototype._animate = function (deltaTime) {
  11033. if (!this._animationStarted)
  11034. return;
  11035. this._time += deltaTime;
  11036. if (this._time > this._delay) {
  11037. this._time = this._time % this._delay;
  11038. this.cellIndex += this._direction;
  11039. if (this.cellIndex == this._toIndex) {
  11040. if (this._loopAnimation) {
  11041. this.cellIndex = this._fromIndex;
  11042. } else {
  11043. this._animationStarted = false;
  11044. if (this.disposeWhenFinishedAnimating) {
  11045. this.dispose();
  11046. }
  11047. }
  11048. }
  11049. }
  11050. };
  11051. Sprite.prototype.dispose = function () {
  11052. for (var i = 0; i < this._manager.sprites.length; i++) {
  11053. if (this._manager.sprites[i] == this) {
  11054. this._manager.sprites.splice(i, 1);
  11055. }
  11056. }
  11057. };
  11058. return Sprite;
  11059. })();
  11060. BABYLON.Sprite = Sprite;
  11061. })(BABYLON || (BABYLON = {}));
  11062. var BABYLON;
  11063. (function (BABYLON) {
  11064. var Layer = (function () {
  11065. function Layer(name, imgUrl, scene, isBackground, color) {
  11066. this.name = name;
  11067. this._vertexDeclaration = [2];
  11068. this._vertexStrideSize = 2 * 4;
  11069. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11070. this.isBackground = isBackground === undefined ? true : isBackground;
  11071. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11072. this._scene = scene;
  11073. this._scene.layers.push(this);
  11074. var vertices = [];
  11075. vertices.push(1, 1);
  11076. vertices.push(-1, 1);
  11077. vertices.push(-1, -1);
  11078. vertices.push(1, -1);
  11079. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11080. var indices = [];
  11081. indices.push(0);
  11082. indices.push(1);
  11083. indices.push(2);
  11084. indices.push(0);
  11085. indices.push(2);
  11086. indices.push(3);
  11087. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11088. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11089. }
  11090. Layer.prototype.render = function () {
  11091. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11092. return;
  11093. var engine = this._scene.getEngine();
  11094. engine.enableEffect(this._effect);
  11095. engine.setState(false);
  11096. this._effect.setTexture("textureSampler", this.texture);
  11097. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11098. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11099. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11100. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11101. engine.draw(true, 0, 6);
  11102. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11103. };
  11104. Layer.prototype.dispose = function () {
  11105. if (this._vertexBuffer) {
  11106. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11107. this._vertexBuffer = null;
  11108. }
  11109. if (this._indexBuffer) {
  11110. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11111. this._indexBuffer = null;
  11112. }
  11113. if (this.texture) {
  11114. this.texture.dispose();
  11115. this.texture = null;
  11116. }
  11117. var index = this._scene.layers.indexOf(this);
  11118. this._scene.layers.splice(index, 1);
  11119. if (this.onDispose) {
  11120. this.onDispose();
  11121. }
  11122. };
  11123. return Layer;
  11124. })();
  11125. BABYLON.Layer = Layer;
  11126. })(BABYLON || (BABYLON = {}));
  11127. var BABYLON;
  11128. (function (BABYLON) {
  11129. var Particle = (function () {
  11130. function Particle() {
  11131. this.position = BABYLON.Vector3.Zero();
  11132. this.direction = BABYLON.Vector3.Zero();
  11133. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11134. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11135. this.lifeTime = 1.0;
  11136. this.age = 0;
  11137. this.size = 0;
  11138. this.angle = 0;
  11139. this.angularSpeed = 0;
  11140. }
  11141. return Particle;
  11142. })();
  11143. BABYLON.Particle = Particle;
  11144. })(BABYLON || (BABYLON = {}));
  11145. var BABYLON;
  11146. (function (BABYLON) {
  11147. var randomNumber = function (min, max) {
  11148. if (min == max) {
  11149. return (min);
  11150. }
  11151. var random = Math.random();
  11152. return ((random * (max - min)) + min);
  11153. };
  11154. var ParticleSystem = (function () {
  11155. function ParticleSystem(name, capacity, scene, fragmentElement) {
  11156. var _this = this;
  11157. this.name = name;
  11158. this.fragmentElement = fragmentElement;
  11159. this.renderingGroupId = 0;
  11160. this.emitter = null;
  11161. this.emitRate = 10;
  11162. this.manualEmitCount = -1;
  11163. this.updateSpeed = 0.01;
  11164. this.targetStopDuration = 0;
  11165. this.disposeOnStop = false;
  11166. this.minEmitPower = 1;
  11167. this.maxEmitPower = 1;
  11168. this.minLifeTime = 1;
  11169. this.maxLifeTime = 1;
  11170. this.minSize = 1;
  11171. this.maxSize = 1;
  11172. this.minAngularSpeed = 0;
  11173. this.maxAngularSpeed = 0;
  11174. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11175. this.forceDepthWrite = false;
  11176. this.gravity = BABYLON.Vector3.Zero();
  11177. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11178. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11179. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11180. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11181. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11182. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11183. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11184. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11185. this.particles = new Array();
  11186. this._vertexDeclaration = [3, 4, 4];
  11187. this._vertexStrideSize = 11 * 4;
  11188. this._stockParticles = new Array();
  11189. this._newPartsExcess = 0;
  11190. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11191. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11192. this._scaledDirection = BABYLON.Vector3.Zero();
  11193. this._scaledGravity = BABYLON.Vector3.Zero();
  11194. this._currentRenderId = -1;
  11195. this._started = false;
  11196. this._stopped = false;
  11197. this._actualFrame = 0;
  11198. this.id = name;
  11199. this._capacity = capacity;
  11200. this._scene = scene;
  11201. scene.particleSystems.push(this);
  11202. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11203. var indices = [];
  11204. var index = 0;
  11205. for (var count = 0; count < capacity; count++) {
  11206. indices.push(index);
  11207. indices.push(index + 1);
  11208. indices.push(index + 2);
  11209. indices.push(index);
  11210. indices.push(index + 2);
  11211. indices.push(index + 3);
  11212. index += 4;
  11213. }
  11214. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11215. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11216. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11217. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11218. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11219. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11220. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11221. };
  11222. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11223. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11224. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11225. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11227. };
  11228. }
  11229. ParticleSystem.prototype.getCapacity = function () {
  11230. return this._capacity;
  11231. };
  11232. ParticleSystem.prototype.isAlive = function () {
  11233. return this._alive;
  11234. };
  11235. ParticleSystem.prototype.isStarted = function () {
  11236. return this._started;
  11237. };
  11238. ParticleSystem.prototype.start = function () {
  11239. this._started = true;
  11240. this._stopped = false;
  11241. this._actualFrame = 0;
  11242. };
  11243. ParticleSystem.prototype.stop = function () {
  11244. this._stopped = true;
  11245. };
  11246. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11247. var offset = index * 11;
  11248. this._vertices[offset] = particle.position.x;
  11249. this._vertices[offset + 1] = particle.position.y;
  11250. this._vertices[offset + 2] = particle.position.z;
  11251. this._vertices[offset + 3] = particle.color.r;
  11252. this._vertices[offset + 4] = particle.color.g;
  11253. this._vertices[offset + 5] = particle.color.b;
  11254. this._vertices[offset + 6] = particle.color.a;
  11255. this._vertices[offset + 7] = particle.angle;
  11256. this._vertices[offset + 8] = particle.size;
  11257. this._vertices[offset + 9] = offsetX;
  11258. this._vertices[offset + 10] = offsetY;
  11259. };
  11260. ParticleSystem.prototype._update = function (newParticles) {
  11261. this._alive = this.particles.length > 0;
  11262. for (var index = 0; index < this.particles.length; index++) {
  11263. var particle = this.particles[index];
  11264. particle.age += this._scaledUpdateSpeed;
  11265. if (particle.age >= particle.lifeTime) {
  11266. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11267. index--;
  11268. continue;
  11269. } else {
  11270. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11271. particle.color.addInPlace(this._scaledColorStep);
  11272. if (particle.color.a < 0)
  11273. particle.color.a = 0;
  11274. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11275. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11276. particle.position.addInPlace(this._scaledDirection);
  11277. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11278. particle.direction.addInPlace(this._scaledGravity);
  11279. }
  11280. }
  11281. var worldMatrix;
  11282. if (this.emitter.position) {
  11283. worldMatrix = this.emitter.getWorldMatrix();
  11284. } else {
  11285. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11286. }
  11287. for (index = 0; index < newParticles; index++) {
  11288. if (this.particles.length == this._capacity) {
  11289. break;
  11290. }
  11291. if (this._stockParticles.length !== 0) {
  11292. particle = this._stockParticles.pop();
  11293. particle.age = 0;
  11294. } else {
  11295. particle = new BABYLON.Particle();
  11296. }
  11297. this.particles.push(particle);
  11298. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11299. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11300. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11301. particle.size = randomNumber(this.minSize, this.maxSize);
  11302. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11303. this.startPositionFunction(worldMatrix, particle.position);
  11304. var step = randomNumber(0, 1.0);
  11305. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11306. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11307. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11308. }
  11309. };
  11310. ParticleSystem.prototype._getEffect = function () {
  11311. var defines = [];
  11312. if (this._scene.clipPlane) {
  11313. defines.push("#define CLIPPLANE");
  11314. }
  11315. var join = defines.join("\n");
  11316. if (this._cachedDefines != join) {
  11317. this._cachedDefines = join;
  11318. var baseName;
  11319. if (this.fragmentElement) {
  11320. baseName = {
  11321. vertex: "particles",
  11322. fragmentElement: this.fragmentElement
  11323. };
  11324. } else {
  11325. baseName = "particles";
  11326. }
  11327. this._effect = this._scene.getEngine().createEffect(baseName, ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11328. }
  11329. return this._effect;
  11330. };
  11331. ParticleSystem.prototype.animate = function () {
  11332. if (!this._started)
  11333. return;
  11334. var effect = this._getEffect();
  11335. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11336. return;
  11337. if (this._currentRenderId === this._scene.getRenderId()) {
  11338. return;
  11339. }
  11340. this._currentRenderId = this._scene.getRenderId();
  11341. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11342. var emitCout;
  11343. if (this.manualEmitCount > -1) {
  11344. emitCout = this.manualEmitCount;
  11345. this.manualEmitCount = 0;
  11346. } else {
  11347. emitCout = this.emitRate;
  11348. }
  11349. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11350. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11351. if (this._newPartsExcess > 1.0) {
  11352. newParticles += this._newPartsExcess >> 0;
  11353. this._newPartsExcess -= this._newPartsExcess >> 0;
  11354. }
  11355. this._alive = false;
  11356. if (!this._stopped) {
  11357. this._actualFrame += this._scaledUpdateSpeed;
  11358. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11359. this.stop();
  11360. } else {
  11361. newParticles = 0;
  11362. }
  11363. this._update(newParticles);
  11364. if (this._stopped) {
  11365. if (!this._alive) {
  11366. this._started = false;
  11367. if (this.disposeOnStop) {
  11368. this._scene._toBeDisposed.push(this);
  11369. }
  11370. }
  11371. }
  11372. var offset = 0;
  11373. for (var index = 0; index < this.particles.length; index++) {
  11374. var particle = this.particles[index];
  11375. this._appendParticleVertex(offset++, particle, 0, 0);
  11376. this._appendParticleVertex(offset++, particle, 1, 0);
  11377. this._appendParticleVertex(offset++, particle, 1, 1);
  11378. this._appendParticleVertex(offset++, particle, 0, 1);
  11379. }
  11380. var engine = this._scene.getEngine();
  11381. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11382. };
  11383. ParticleSystem.prototype.render = function () {
  11384. var effect = this._getEffect();
  11385. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11386. return 0;
  11387. var engine = this._scene.getEngine();
  11388. engine.enableEffect(effect);
  11389. var viewMatrix = this._scene.getViewMatrix();
  11390. effect.setTexture("diffuseSampler", this.particleTexture);
  11391. effect.setMatrix("view", viewMatrix);
  11392. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11393. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11394. if (this._scene.clipPlane) {
  11395. var clipPlane = this._scene.clipPlane;
  11396. var invView = viewMatrix.clone();
  11397. invView.invert();
  11398. effect.setMatrix("invView", invView);
  11399. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11400. }
  11401. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11402. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11403. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11404. } else {
  11405. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11406. }
  11407. if (this.forceDepthWrite) {
  11408. engine.setDepthWrite(true);
  11409. }
  11410. engine.draw(true, 0, this.particles.length * 6);
  11411. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11412. return this.particles.length;
  11413. };
  11414. ParticleSystem.prototype.dispose = function () {
  11415. if (this._vertexBuffer) {
  11416. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11417. this._vertexBuffer = null;
  11418. }
  11419. if (this._indexBuffer) {
  11420. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11421. this._indexBuffer = null;
  11422. }
  11423. if (this.particleTexture) {
  11424. this.particleTexture.dispose();
  11425. this.particleTexture = null;
  11426. }
  11427. var index = this._scene.particleSystems.indexOf(this);
  11428. this._scene.particleSystems.splice(index, 1);
  11429. if (this.onDispose) {
  11430. this.onDispose();
  11431. }
  11432. };
  11433. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11434. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11435. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11436. if (newEmitter === undefined) {
  11437. newEmitter = this.emitter;
  11438. }
  11439. result.emitter = newEmitter;
  11440. if (this.particleTexture) {
  11441. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11442. }
  11443. result.start();
  11444. return result;
  11445. };
  11446. ParticleSystem.BLENDMODE_ONEONE = 0;
  11447. ParticleSystem.BLENDMODE_STANDARD = 1;
  11448. return ParticleSystem;
  11449. })();
  11450. BABYLON.ParticleSystem = ParticleSystem;
  11451. })(BABYLON || (BABYLON = {}));
  11452. var BABYLON;
  11453. (function (BABYLON) {
  11454. var Animation = (function () {
  11455. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11456. this.name = name;
  11457. this.targetProperty = targetProperty;
  11458. this.framePerSecond = framePerSecond;
  11459. this.dataType = dataType;
  11460. this.loopMode = loopMode;
  11461. this._offsetsCache = {};
  11462. this._highLimitsCache = {};
  11463. this._stopped = false;
  11464. this.targetPropertyPath = targetProperty.split(".");
  11465. this.dataType = dataType;
  11466. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11467. }
  11468. Animation.prototype.isStopped = function () {
  11469. return this._stopped;
  11470. };
  11471. Animation.prototype.getKeys = function () {
  11472. return this._keys;
  11473. };
  11474. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11475. return startValue + (endValue - startValue) * gradient;
  11476. };
  11477. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11478. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11479. };
  11480. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11481. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11482. };
  11483. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11484. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11485. };
  11486. Animation.prototype.clone = function () {
  11487. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11488. clone.setKeys(this._keys);
  11489. return clone;
  11490. };
  11491. Animation.prototype.setKeys = function (values) {
  11492. this._keys = values.slice(0);
  11493. this._offsetsCache = {};
  11494. this._highLimitsCache = {};
  11495. };
  11496. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11497. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11498. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11499. }
  11500. this.currentFrame = currentFrame;
  11501. for (var key = 0; key < this._keys.length; key++) {
  11502. if (this._keys[key + 1].frame >= currentFrame) {
  11503. var startValue = this._keys[key].value;
  11504. var endValue = this._keys[key + 1].value;
  11505. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11506. switch (this.dataType) {
  11507. case Animation.ANIMATIONTYPE_FLOAT:
  11508. switch (loopMode) {
  11509. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11510. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11511. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11512. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11513. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11514. }
  11515. break;
  11516. case Animation.ANIMATIONTYPE_QUATERNION:
  11517. var quaternion = null;
  11518. switch (loopMode) {
  11519. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11520. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11521. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11522. break;
  11523. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11524. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11525. break;
  11526. }
  11527. return quaternion;
  11528. case Animation.ANIMATIONTYPE_VECTOR3:
  11529. switch (loopMode) {
  11530. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11531. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11532. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11533. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11534. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11535. }
  11536. case Animation.ANIMATIONTYPE_COLOR3:
  11537. switch (loopMode) {
  11538. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11539. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11540. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11541. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11542. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11543. }
  11544. case Animation.ANIMATIONTYPE_MATRIX:
  11545. switch (loopMode) {
  11546. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11547. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11548. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11549. return startValue;
  11550. }
  11551. default:
  11552. break;
  11553. }
  11554. break;
  11555. }
  11556. }
  11557. return this._keys[this._keys.length - 1].value;
  11558. };
  11559. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11560. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11561. this._stopped = true;
  11562. return false;
  11563. }
  11564. var returnValue = true;
  11565. if (this._keys[0].frame != 0) {
  11566. var newKey = {
  11567. frame: 0,
  11568. value: this._keys[0].value
  11569. };
  11570. this._keys.splice(0, 0, newKey);
  11571. }
  11572. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11573. from = this._keys[0].frame;
  11574. }
  11575. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11576. to = this._keys[this._keys.length - 1].frame;
  11577. }
  11578. var range = to - from;
  11579. var offsetValue;
  11580. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11581. if (ratio > range && !loop) {
  11582. returnValue = false;
  11583. highLimitValue = this._keys[this._keys.length - 1].value;
  11584. } else {
  11585. var highLimitValue = 0;
  11586. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11587. var keyOffset = to.toString() + from.toString();
  11588. if (!this._offsetsCache[keyOffset]) {
  11589. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11590. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11591. switch (this.dataType) {
  11592. case Animation.ANIMATIONTYPE_FLOAT:
  11593. this._offsetsCache[keyOffset] = toValue - fromValue;
  11594. break;
  11595. case Animation.ANIMATIONTYPE_QUATERNION:
  11596. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11597. break;
  11598. case Animation.ANIMATIONTYPE_VECTOR3:
  11599. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11600. case Animation.ANIMATIONTYPE_COLOR3:
  11601. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11602. default:
  11603. break;
  11604. }
  11605. this._highLimitsCache[keyOffset] = toValue;
  11606. }
  11607. highLimitValue = this._highLimitsCache[keyOffset];
  11608. offsetValue = this._offsetsCache[keyOffset];
  11609. }
  11610. }
  11611. if (offsetValue === undefined) {
  11612. switch (this.dataType) {
  11613. case Animation.ANIMATIONTYPE_FLOAT:
  11614. offsetValue = 0;
  11615. break;
  11616. case Animation.ANIMATIONTYPE_QUATERNION:
  11617. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11618. break;
  11619. case Animation.ANIMATIONTYPE_VECTOR3:
  11620. offsetValue = BABYLON.Vector3.Zero();
  11621. break;
  11622. case Animation.ANIMATIONTYPE_COLOR3:
  11623. offsetValue = BABYLON.Color3.Black();
  11624. }
  11625. }
  11626. var repeatCount = (ratio / range) >> 0;
  11627. var currentFrame = returnValue ? from + ratio % range : to;
  11628. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11629. if (this.targetPropertyPath.length > 1) {
  11630. var property = this._target[this.targetPropertyPath[0]];
  11631. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11632. property = property[this.targetPropertyPath[index]];
  11633. }
  11634. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11635. } else {
  11636. this._target[this.targetPropertyPath[0]] = currentValue;
  11637. }
  11638. if (this._target.markAsDirty) {
  11639. this._target.markAsDirty(this.targetProperty);
  11640. }
  11641. if (!returnValue) {
  11642. this._stopped = true;
  11643. }
  11644. return returnValue;
  11645. };
  11646. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11647. get: function () {
  11648. return Animation._ANIMATIONTYPE_FLOAT;
  11649. },
  11650. enumerable: true,
  11651. configurable: true
  11652. });
  11653. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11654. get: function () {
  11655. return Animation._ANIMATIONTYPE_VECTOR3;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11661. get: function () {
  11662. return Animation._ANIMATIONTYPE_QUATERNION;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11668. get: function () {
  11669. return Animation._ANIMATIONTYPE_MATRIX;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11675. get: function () {
  11676. return Animation._ANIMATIONTYPE_COLOR3;
  11677. },
  11678. enumerable: true,
  11679. configurable: true
  11680. });
  11681. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11682. get: function () {
  11683. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11689. get: function () {
  11690. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11696. get: function () {
  11697. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11698. },
  11699. enumerable: true,
  11700. configurable: true
  11701. });
  11702. Animation._ANIMATIONTYPE_FLOAT = 0;
  11703. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11704. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11705. Animation._ANIMATIONTYPE_MATRIX = 3;
  11706. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11707. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11708. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11709. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11710. return Animation;
  11711. })();
  11712. BABYLON.Animation = Animation;
  11713. })(BABYLON || (BABYLON = {}));
  11714. var BABYLON;
  11715. (function (BABYLON) {
  11716. var Animatable = (function () {
  11717. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11718. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11719. if (typeof toFrame === "undefined") { toFrame = 100; }
  11720. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11721. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11722. this.target = target;
  11723. this.fromFrame = fromFrame;
  11724. this.toFrame = toFrame;
  11725. this.loopAnimation = loopAnimation;
  11726. this.speedRatio = speedRatio;
  11727. this.onAnimationEnd = onAnimationEnd;
  11728. this._animations = new Array();
  11729. this._paused = false;
  11730. this.animationStarted = false;
  11731. if (animations) {
  11732. this.appendAnimations(target, animations);
  11733. }
  11734. this._scene = scene;
  11735. scene._activeAnimatables.push(this);
  11736. }
  11737. Animatable.prototype.appendAnimations = function (target, animations) {
  11738. for (var index = 0; index < animations.length; index++) {
  11739. var animation = animations[index];
  11740. animation._target = target;
  11741. this._animations.push(animation);
  11742. }
  11743. };
  11744. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11745. var animations = this._animations;
  11746. for (var index = 0; index < animations.length; index++) {
  11747. if (animations[index].targetProperty === property) {
  11748. return animations[index];
  11749. }
  11750. }
  11751. return null;
  11752. };
  11753. Animatable.prototype.pause = function () {
  11754. this._paused = true;
  11755. };
  11756. Animatable.prototype.restart = function () {
  11757. this._paused = false;
  11758. };
  11759. Animatable.prototype.stop = function () {
  11760. var index = this._scene._activeAnimatables.indexOf(this);
  11761. if (index > -1) {
  11762. this._scene._activeAnimatables.splice(index, 1);
  11763. }
  11764. if (this.onAnimationEnd) {
  11765. this.onAnimationEnd();
  11766. }
  11767. };
  11768. Animatable.prototype._animate = function (delay) {
  11769. if (this._paused) {
  11770. return true;
  11771. }
  11772. if (!this._localDelayOffset) {
  11773. this._localDelayOffset = delay;
  11774. }
  11775. var running = false;
  11776. var animations = this._animations;
  11777. for (var index = 0; index < animations.length; index++) {
  11778. var animation = animations[index];
  11779. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11780. running = running || isRunning;
  11781. }
  11782. if (!running && this.onAnimationEnd) {
  11783. this.onAnimationEnd();
  11784. }
  11785. return running;
  11786. };
  11787. return Animatable;
  11788. })();
  11789. BABYLON.Animatable = Animatable;
  11790. })(BABYLON || (BABYLON = {}));
  11791. var BABYLON;
  11792. (function (BABYLON) {
  11793. var Octree = (function () {
  11794. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11795. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11796. this.maxDepth = maxDepth;
  11797. this.dynamicContent = new Array();
  11798. this._maxBlockCapacity = maxBlockCapacity || 64;
  11799. this._selectionContent = new BABYLON.SmartArray(1024);
  11800. this._creationFunc = creationFunc;
  11801. }
  11802. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11803. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11804. };
  11805. Octree.prototype.addMesh = function (entry) {
  11806. for (var index = 0; index < this.blocks.length; index++) {
  11807. var block = this.blocks[index];
  11808. block.addEntry(entry);
  11809. }
  11810. };
  11811. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11812. this._selectionContent.reset();
  11813. for (var index = 0; index < this.blocks.length; index++) {
  11814. var block = this.blocks[index];
  11815. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11816. }
  11817. if (allowDuplicate) {
  11818. this._selectionContent.concat(this.dynamicContent);
  11819. } else {
  11820. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11821. }
  11822. return this._selectionContent;
  11823. };
  11824. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11825. this._selectionContent.reset();
  11826. for (var index = 0; index < this.blocks.length; index++) {
  11827. var block = this.blocks[index];
  11828. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11829. }
  11830. if (allowDuplicate) {
  11831. this._selectionContent.concat(this.dynamicContent);
  11832. } else {
  11833. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11834. }
  11835. return this._selectionContent;
  11836. };
  11837. Octree.prototype.intersectsRay = function (ray) {
  11838. this._selectionContent.reset();
  11839. for (var index = 0; index < this.blocks.length; index++) {
  11840. var block = this.blocks[index];
  11841. block.intersectsRay(ray, this._selectionContent);
  11842. }
  11843. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11844. return this._selectionContent;
  11845. };
  11846. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11847. target.blocks = new Array();
  11848. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11849. for (var x = 0; x < 2; x++) {
  11850. for (var y = 0; y < 2; y++) {
  11851. for (var z = 0; z < 2; z++) {
  11852. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11853. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11854. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11855. block.addEntries(entries);
  11856. target.blocks.push(block);
  11857. }
  11858. }
  11859. }
  11860. };
  11861. Octree.CreationFuncForMeshes = function (entry, block) {
  11862. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11863. block.entries.push(entry);
  11864. }
  11865. };
  11866. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11867. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11868. block.entries.push(entry);
  11869. }
  11870. };
  11871. return Octree;
  11872. })();
  11873. BABYLON.Octree = Octree;
  11874. })(BABYLON || (BABYLON = {}));
  11875. var BABYLON;
  11876. (function (BABYLON) {
  11877. var OctreeBlock = (function () {
  11878. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11879. this.entries = new Array();
  11880. this._boundingVectors = new Array();
  11881. this._capacity = capacity;
  11882. this._depth = depth;
  11883. this._maxDepth = maxDepth;
  11884. this._creationFunc = creationFunc;
  11885. this._minPoint = minPoint;
  11886. this._maxPoint = maxPoint;
  11887. this._boundingVectors.push(minPoint.clone());
  11888. this._boundingVectors.push(maxPoint.clone());
  11889. this._boundingVectors.push(minPoint.clone());
  11890. this._boundingVectors[2].x = maxPoint.x;
  11891. this._boundingVectors.push(minPoint.clone());
  11892. this._boundingVectors[3].y = maxPoint.y;
  11893. this._boundingVectors.push(minPoint.clone());
  11894. this._boundingVectors[4].z = maxPoint.z;
  11895. this._boundingVectors.push(maxPoint.clone());
  11896. this._boundingVectors[5].z = minPoint.z;
  11897. this._boundingVectors.push(maxPoint.clone());
  11898. this._boundingVectors[6].x = minPoint.x;
  11899. this._boundingVectors.push(maxPoint.clone());
  11900. this._boundingVectors[7].y = minPoint.y;
  11901. }
  11902. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11903. get: function () {
  11904. return this._capacity;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11910. get: function () {
  11911. return this._minPoint;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11917. get: function () {
  11918. return this._maxPoint;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. OctreeBlock.prototype.addEntry = function (entry) {
  11924. if (this.blocks) {
  11925. for (var index = 0; index < this.blocks.length; index++) {
  11926. var block = this.blocks[index];
  11927. block.addEntry(entry);
  11928. }
  11929. return;
  11930. }
  11931. this._creationFunc(entry, this);
  11932. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11933. this.createInnerBlocks();
  11934. }
  11935. };
  11936. OctreeBlock.prototype.addEntries = function (entries) {
  11937. for (var index = 0; index < entries.length; index++) {
  11938. var mesh = entries[index];
  11939. this.addEntry(mesh);
  11940. }
  11941. };
  11942. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11943. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11944. if (this.blocks) {
  11945. for (var index = 0; index < this.blocks.length; index++) {
  11946. var block = this.blocks[index];
  11947. block.select(frustumPlanes, selection, allowDuplicate);
  11948. }
  11949. return;
  11950. }
  11951. if (allowDuplicate) {
  11952. selection.concat(this.entries);
  11953. } else {
  11954. selection.concatWithNoDuplicate(this.entries);
  11955. }
  11956. }
  11957. };
  11958. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  11959. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  11960. if (this.blocks) {
  11961. for (var index = 0; index < this.blocks.length; index++) {
  11962. var block = this.blocks[index];
  11963. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  11964. }
  11965. return;
  11966. }
  11967. if (allowDuplicate) {
  11968. selection.concat(this.entries);
  11969. } else {
  11970. selection.concatWithNoDuplicate(this.entries);
  11971. }
  11972. }
  11973. };
  11974. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  11975. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  11976. if (this.blocks) {
  11977. for (var index = 0; index < this.blocks.length; index++) {
  11978. var block = this.blocks[index];
  11979. block.intersectsRay(ray, selection);
  11980. }
  11981. return;
  11982. }
  11983. selection.concatWithNoDuplicate(this.entries);
  11984. }
  11985. };
  11986. OctreeBlock.prototype.createInnerBlocks = function () {
  11987. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  11988. };
  11989. return OctreeBlock;
  11990. })();
  11991. BABYLON.OctreeBlock = OctreeBlock;
  11992. })(BABYLON || (BABYLON = {}));
  11993. var BABYLON;
  11994. (function (BABYLON) {
  11995. var Bone = (function () {
  11996. function Bone(name, skeleton, parentBone, matrix) {
  11997. this.name = name;
  11998. this.children = new Array();
  11999. this.animations = new Array();
  12000. this._worldTransform = new BABYLON.Matrix();
  12001. this._absoluteTransform = new BABYLON.Matrix();
  12002. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12003. this._skeleton = skeleton;
  12004. this._matrix = matrix;
  12005. this._baseMatrix = matrix;
  12006. skeleton.bones.push(this);
  12007. if (parentBone) {
  12008. this._parent = parentBone;
  12009. parentBone.children.push(this);
  12010. } else {
  12011. this._parent = null;
  12012. }
  12013. this._updateDifferenceMatrix();
  12014. }
  12015. Bone.prototype.getParent = function () {
  12016. return this._parent;
  12017. };
  12018. Bone.prototype.getLocalMatrix = function () {
  12019. return this._matrix;
  12020. };
  12021. Bone.prototype.getBaseMatrix = function () {
  12022. return this._baseMatrix;
  12023. };
  12024. Bone.prototype.getWorldMatrix = function () {
  12025. return this._worldTransform;
  12026. };
  12027. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12028. return this._invertedAbsoluteTransform;
  12029. };
  12030. Bone.prototype.getAbsoluteMatrix = function () {
  12031. var matrix = this._matrix.clone();
  12032. var parent = this._parent;
  12033. while (parent) {
  12034. matrix = matrix.multiply(parent.getLocalMatrix());
  12035. parent = parent.getParent();
  12036. }
  12037. return matrix;
  12038. };
  12039. Bone.prototype.updateMatrix = function (matrix) {
  12040. this._matrix = matrix;
  12041. this._skeleton._markAsDirty();
  12042. this._updateDifferenceMatrix();
  12043. };
  12044. Bone.prototype._updateDifferenceMatrix = function () {
  12045. if (this._parent) {
  12046. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12047. } else {
  12048. this._absoluteTransform.copyFrom(this._matrix);
  12049. }
  12050. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12051. for (var index = 0; index < this.children.length; index++) {
  12052. this.children[index]._updateDifferenceMatrix();
  12053. }
  12054. };
  12055. Bone.prototype.markAsDirty = function () {
  12056. this._skeleton._markAsDirty();
  12057. };
  12058. return Bone;
  12059. })();
  12060. BABYLON.Bone = Bone;
  12061. })(BABYLON || (BABYLON = {}));
  12062. var BABYLON;
  12063. (function (BABYLON) {
  12064. var Skeleton = (function () {
  12065. function Skeleton(name, id, scene) {
  12066. this.name = name;
  12067. this.id = id;
  12068. this.bones = new Array();
  12069. this._isDirty = true;
  12070. this._identity = BABYLON.Matrix.Identity();
  12071. this.bones = [];
  12072. this._scene = scene;
  12073. scene.skeletons.push(this);
  12074. }
  12075. Skeleton.prototype.getTransformMatrices = function () {
  12076. return this._transformMatrices;
  12077. };
  12078. Skeleton.prototype._markAsDirty = function () {
  12079. this._isDirty = true;
  12080. };
  12081. Skeleton.prototype.prepare = function () {
  12082. if (!this._isDirty) {
  12083. return;
  12084. }
  12085. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12086. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12087. }
  12088. for (var index = 0; index < this.bones.length; index++) {
  12089. var bone = this.bones[index];
  12090. var parentBone = bone.getParent();
  12091. if (parentBone) {
  12092. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12093. } else {
  12094. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12095. }
  12096. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12097. }
  12098. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12099. this._isDirty = false;
  12100. };
  12101. Skeleton.prototype.getAnimatables = function () {
  12102. if (!this._animatables || this._animatables.length != this.bones.length) {
  12103. this._animatables = [];
  12104. for (var index = 0; index < this.bones.length; index++) {
  12105. this._animatables.push(this.bones[index]);
  12106. }
  12107. }
  12108. return this._animatables;
  12109. };
  12110. Skeleton.prototype.clone = function (name, id) {
  12111. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12112. for (var index = 0; index < this.bones.length; index++) {
  12113. var source = this.bones[index];
  12114. var parentBone = null;
  12115. if (source.getParent()) {
  12116. var parentIndex = this.bones.indexOf(source.getParent());
  12117. parentBone = result.bones[parentIndex];
  12118. }
  12119. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12120. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12121. }
  12122. return result;
  12123. };
  12124. return Skeleton;
  12125. })();
  12126. BABYLON.Skeleton = Skeleton;
  12127. })(BABYLON || (BABYLON = {}));
  12128. var BABYLON;
  12129. (function (BABYLON) {
  12130. var PostProcess = (function () {
  12131. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12132. this.name = name;
  12133. this.width = -1;
  12134. this.height = -1;
  12135. this._reusable = false;
  12136. this._textures = new BABYLON.SmartArray(2);
  12137. this._currentRenderTextureInd = 0;
  12138. if (camera != null) {
  12139. this._camera = camera;
  12140. this._scene = camera.getScene();
  12141. camera.attachPostProcess(this);
  12142. this._engine = this._scene.getEngine();
  12143. } else {
  12144. this._engine = engine;
  12145. }
  12146. this._renderRatio = ratio;
  12147. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12148. this._reusable = reusable || false;
  12149. samplers = samplers || [];
  12150. samplers.push("textureSampler");
  12151. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12152. }
  12153. PostProcess.prototype.isReusable = function () {
  12154. return this._reusable;
  12155. };
  12156. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12157. camera = camera || this._camera;
  12158. var scene = camera.getScene();
  12159. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12160. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12161. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12162. if (this._textures.length > 0) {
  12163. for (var i = 0; i < this._textures.length; i++) {
  12164. this._engine._releaseTexture(this._textures.data[i]);
  12165. }
  12166. this._textures.reset();
  12167. }
  12168. this.width = desiredWidth;
  12169. this.height = desiredHeight;
  12170. 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 }));
  12171. if (this._reusable) {
  12172. 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 }));
  12173. }
  12174. if (this.onSizeChanged) {
  12175. this.onSizeChanged();
  12176. }
  12177. }
  12178. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12179. if (this.onActivate) {
  12180. this.onActivate(camera);
  12181. }
  12182. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12183. if (this._reusable) {
  12184. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12185. }
  12186. };
  12187. PostProcess.prototype.apply = function () {
  12188. if (!this._effect.isReady())
  12189. return null;
  12190. this._engine.enableEffect(this._effect);
  12191. this._engine.setState(false);
  12192. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12193. this._engine.setDepthBuffer(false);
  12194. this._engine.setDepthWrite(false);
  12195. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12196. if (this.onApply) {
  12197. this.onApply(this._effect);
  12198. }
  12199. return this._effect;
  12200. };
  12201. PostProcess.prototype.dispose = function (camera) {
  12202. camera = camera || this._camera;
  12203. if (this._textures.length > 0) {
  12204. for (var i = 0; i < this._textures.length; i++) {
  12205. this._engine._releaseTexture(this._textures.data[i]);
  12206. }
  12207. this._textures.reset();
  12208. }
  12209. camera.detachPostProcess(this);
  12210. var index = camera._postProcesses.indexOf(this);
  12211. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12212. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12213. }
  12214. };
  12215. return PostProcess;
  12216. })();
  12217. BABYLON.PostProcess = PostProcess;
  12218. })(BABYLON || (BABYLON = {}));
  12219. var BABYLON;
  12220. (function (BABYLON) {
  12221. var PostProcessManager = (function () {
  12222. function PostProcessManager(scene) {
  12223. this._vertexDeclaration = [2];
  12224. this._vertexStrideSize = 2 * 4;
  12225. this._scene = scene;
  12226. var vertices = [];
  12227. vertices.push(1, 1);
  12228. vertices.push(-1, 1);
  12229. vertices.push(-1, -1);
  12230. vertices.push(1, -1);
  12231. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12232. var indices = [];
  12233. indices.push(0);
  12234. indices.push(1);
  12235. indices.push(2);
  12236. indices.push(0);
  12237. indices.push(2);
  12238. indices.push(3);
  12239. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12240. }
  12241. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12242. var postProcesses = this._scene.activeCamera._postProcesses;
  12243. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12244. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12245. return false;
  12246. }
  12247. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12248. return true;
  12249. };
  12250. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12251. var postProcesses = this._scene.activeCamera._postProcesses;
  12252. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12253. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12254. return;
  12255. }
  12256. var engine = this._scene.getEngine();
  12257. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12258. if (index < postProcessesTakenIndices.length - 1) {
  12259. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12260. } else {
  12261. if (targetTexture) {
  12262. engine.bindFramebuffer(targetTexture);
  12263. } else {
  12264. engine.restoreDefaultFramebuffer();
  12265. }
  12266. }
  12267. if (doNotPresent) {
  12268. break;
  12269. }
  12270. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12271. if (effect) {
  12272. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12273. engine.draw(true, 0, 6);
  12274. }
  12275. }
  12276. engine.setDepthBuffer(true);
  12277. engine.setDepthWrite(true);
  12278. };
  12279. PostProcessManager.prototype.dispose = function () {
  12280. if (this._vertexBuffer) {
  12281. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12282. this._vertexBuffer = null;
  12283. }
  12284. if (this._indexBuffer) {
  12285. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12286. this._indexBuffer = null;
  12287. }
  12288. };
  12289. return PostProcessManager;
  12290. })();
  12291. BABYLON.PostProcessManager = PostProcessManager;
  12292. })(BABYLON || (BABYLON = {}));
  12293. var __extends = this.__extends || function (d, b) {
  12294. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12295. function __() { this.constructor = d; }
  12296. __.prototype = b.prototype;
  12297. d.prototype = new __();
  12298. };
  12299. var BABYLON;
  12300. (function (BABYLON) {
  12301. var PassPostProcess = (function (_super) {
  12302. __extends(PassPostProcess, _super);
  12303. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12304. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12305. }
  12306. return PassPostProcess;
  12307. })(BABYLON.PostProcess);
  12308. BABYLON.PassPostProcess = PassPostProcess;
  12309. })(BABYLON || (BABYLON = {}));
  12310. var __extends = this.__extends || function (d, b) {
  12311. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12312. function __() { this.constructor = d; }
  12313. __.prototype = b.prototype;
  12314. d.prototype = new __();
  12315. };
  12316. var BABYLON;
  12317. (function (BABYLON) {
  12318. var BlurPostProcess = (function (_super) {
  12319. __extends(BlurPostProcess, _super);
  12320. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12321. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12322. var _this = this;
  12323. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12324. this.direction = direction;
  12325. this.blurWidth = blurWidth;
  12326. this.onApply = function (effect) {
  12327. effect.setFloat2("screenSize", _this.width, _this.height);
  12328. effect.setVector2("direction", _this.direction);
  12329. effect.setFloat("blurWidth", _this.blurWidth);
  12330. };
  12331. }
  12332. return BlurPostProcess;
  12333. })(BABYLON.PostProcess);
  12334. BABYLON.BlurPostProcess = BlurPostProcess;
  12335. })(BABYLON || (BABYLON = {}));
  12336. var __extends = this.__extends || function (d, b) {
  12337. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12338. function __() { this.constructor = d; }
  12339. __.prototype = b.prototype;
  12340. d.prototype = new __();
  12341. };
  12342. var BABYLON;
  12343. (function (BABYLON) {
  12344. var FilterPostProcess = (function (_super) {
  12345. __extends(FilterPostProcess, _super);
  12346. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12347. var _this = this;
  12348. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12349. this.kernelMatrix = kernelMatrix;
  12350. this.onApply = function (effect) {
  12351. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12352. };
  12353. }
  12354. return FilterPostProcess;
  12355. })(BABYLON.PostProcess);
  12356. BABYLON.FilterPostProcess = FilterPostProcess;
  12357. })(BABYLON || (BABYLON = {}));
  12358. var __extends = this.__extends || function (d, b) {
  12359. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12360. function __() { this.constructor = d; }
  12361. __.prototype = b.prototype;
  12362. d.prototype = new __();
  12363. };
  12364. var BABYLON;
  12365. (function (BABYLON) {
  12366. var RefractionPostProcess = (function (_super) {
  12367. __extends(RefractionPostProcess, _super);
  12368. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12369. var _this = this;
  12370. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12371. this.color = color;
  12372. this.depth = depth;
  12373. this.colorLevel = colorLevel;
  12374. this.onActivate = function (cam) {
  12375. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12376. };
  12377. this.onApply = function (effect) {
  12378. effect.setColor3("baseColor", _this.color);
  12379. effect.setFloat("depth", _this.depth);
  12380. effect.setFloat("colorLevel", _this.colorLevel);
  12381. effect.setTexture("refractionSampler", _this._refRexture);
  12382. };
  12383. }
  12384. RefractionPostProcess.prototype.dispose = function (camera) {
  12385. if (this._refRexture) {
  12386. this._refRexture.dispose();
  12387. }
  12388. _super.prototype.dispose.call(this, camera);
  12389. };
  12390. return RefractionPostProcess;
  12391. })(BABYLON.PostProcess);
  12392. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12393. })(BABYLON || (BABYLON = {}));
  12394. var __extends = this.__extends || function (d, b) {
  12395. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12396. function __() { this.constructor = d; }
  12397. __.prototype = b.prototype;
  12398. d.prototype = new __();
  12399. };
  12400. var BABYLON;
  12401. (function (BABYLON) {
  12402. var BlackAndWhitePostProcess = (function (_super) {
  12403. __extends(BlackAndWhitePostProcess, _super);
  12404. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12405. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12406. }
  12407. return BlackAndWhitePostProcess;
  12408. })(BABYLON.PostProcess);
  12409. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12410. })(BABYLON || (BABYLON = {}));
  12411. var __extends = this.__extends || function (d, b) {
  12412. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12413. function __() { this.constructor = d; }
  12414. __.prototype = b.prototype;
  12415. d.prototype = new __();
  12416. };
  12417. var BABYLON;
  12418. (function (BABYLON) {
  12419. var ConvolutionPostProcess = (function (_super) {
  12420. __extends(ConvolutionPostProcess, _super);
  12421. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12422. var _this = this;
  12423. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12424. this.kernel = kernel;
  12425. this.onApply = function (effect) {
  12426. effect.setFloat2("screenSize", _this.width, _this.height);
  12427. effect.setArray("kernel", _this.kernel);
  12428. };
  12429. }
  12430. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12431. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12432. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12433. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12434. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12435. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12436. return ConvolutionPostProcess;
  12437. })(BABYLON.PostProcess);
  12438. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12439. })(BABYLON || (BABYLON = {}));
  12440. var __extends = this.__extends || function (d, b) {
  12441. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12442. function __() { this.constructor = d; }
  12443. __.prototype = b.prototype;
  12444. d.prototype = new __();
  12445. };
  12446. var BABYLON;
  12447. (function (BABYLON) {
  12448. var FxaaPostProcess = (function (_super) {
  12449. __extends(FxaaPostProcess, _super);
  12450. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12451. var _this = this;
  12452. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12453. this.onSizeChanged = function () {
  12454. _this.texelWidth = 1.0 / _this.width;
  12455. _this.texelHeight = 1.0 / _this.height;
  12456. };
  12457. this.onApply = function (effect) {
  12458. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12459. };
  12460. }
  12461. return FxaaPostProcess;
  12462. })(BABYLON.PostProcess);
  12463. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12464. })(BABYLON || (BABYLON = {}));
  12465. var BABYLON;
  12466. (function (BABYLON) {
  12467. var LensFlare = (function () {
  12468. function LensFlare(size, position, color, imgUrl, system) {
  12469. this.size = size;
  12470. this.position = position;
  12471. this.dispose = function () {
  12472. if (this.texture) {
  12473. this.texture.dispose();
  12474. }
  12475. var index = this._system.lensFlares.indexOf(this);
  12476. this._system.lensFlares.splice(index, 1);
  12477. };
  12478. this.color = color || new BABYLON.Color3(1, 1, 1);
  12479. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12480. this._system = system;
  12481. system.lensFlares.push(this);
  12482. }
  12483. return LensFlare;
  12484. })();
  12485. BABYLON.LensFlare = LensFlare;
  12486. })(BABYLON || (BABYLON = {}));
  12487. var BABYLON;
  12488. (function (BABYLON) {
  12489. var LensFlareSystem = (function () {
  12490. function LensFlareSystem(name, emitter, scene) {
  12491. this.name = name;
  12492. this.lensFlares = new Array();
  12493. this.borderLimit = 300;
  12494. this._vertexDeclaration = [2];
  12495. this._vertexStrideSize = 2 * 4;
  12496. this._isEnabled = true;
  12497. this._scene = scene;
  12498. this._emitter = emitter;
  12499. scene.lensFlareSystems.push(this);
  12500. this.meshesSelectionPredicate = function (m) {
  12501. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12502. };
  12503. var vertices = [];
  12504. vertices.push(1, 1);
  12505. vertices.push(-1, 1);
  12506. vertices.push(-1, -1);
  12507. vertices.push(1, -1);
  12508. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12509. var indices = [];
  12510. indices.push(0);
  12511. indices.push(1);
  12512. indices.push(2);
  12513. indices.push(0);
  12514. indices.push(2);
  12515. indices.push(3);
  12516. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12517. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12518. }
  12519. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12520. get: function () {
  12521. return this._isEnabled;
  12522. },
  12523. set: function (value) {
  12524. this._isEnabled = value;
  12525. },
  12526. enumerable: true,
  12527. configurable: true
  12528. });
  12529. LensFlareSystem.prototype.getScene = function () {
  12530. return this._scene;
  12531. };
  12532. LensFlareSystem.prototype.getEmitter = function () {
  12533. return this._emitter;
  12534. };
  12535. LensFlareSystem.prototype.getEmitterPosition = function () {
  12536. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12537. };
  12538. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12539. var position = this.getEmitterPosition();
  12540. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12541. this._positionX = position.x;
  12542. this._positionY = position.y;
  12543. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12544. if (position.z > 0) {
  12545. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12546. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12547. return true;
  12548. }
  12549. }
  12550. return false;
  12551. };
  12552. LensFlareSystem.prototype._isVisible = function () {
  12553. if (!this._isEnabled) {
  12554. return false;
  12555. }
  12556. var emitterPosition = this.getEmitterPosition();
  12557. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12558. var distance = direction.length();
  12559. direction.normalize();
  12560. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12561. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12562. return !pickInfo.hit || pickInfo.distance > distance;
  12563. };
  12564. LensFlareSystem.prototype.render = function () {
  12565. if (!this._effect.isReady())
  12566. return false;
  12567. var engine = this._scene.getEngine();
  12568. var viewport = this._scene.activeCamera.viewport;
  12569. var globalViewport = viewport.toGlobal(engine);
  12570. if (!this.computeEffectivePosition(globalViewport)) {
  12571. return false;
  12572. }
  12573. if (!this._isVisible()) {
  12574. return false;
  12575. }
  12576. var awayX;
  12577. var awayY;
  12578. if (this._positionX < this.borderLimit + globalViewport.x) {
  12579. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12580. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12581. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12582. } else {
  12583. awayX = 0;
  12584. }
  12585. if (this._positionY < this.borderLimit + globalViewport.y) {
  12586. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12587. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12588. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12589. } else {
  12590. awayY = 0;
  12591. }
  12592. var away = (awayX > awayY) ? awayX : awayY;
  12593. if (away > this.borderLimit) {
  12594. away = this.borderLimit;
  12595. }
  12596. var intensity = 1.0 - (away / this.borderLimit);
  12597. if (intensity < 0) {
  12598. return false;
  12599. }
  12600. if (intensity > 1.0) {
  12601. intensity = 1.0;
  12602. }
  12603. var centerX = globalViewport.x + globalViewport.width / 2;
  12604. var centerY = globalViewport.y + globalViewport.height / 2;
  12605. var distX = centerX - this._positionX;
  12606. var distY = centerY - this._positionY;
  12607. engine.enableEffect(this._effect);
  12608. engine.setState(false);
  12609. engine.setDepthBuffer(false);
  12610. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12611. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12612. for (var index = 0; index < this.lensFlares.length; index++) {
  12613. var flare = this.lensFlares[index];
  12614. var x = centerX - (distX * flare.position);
  12615. var y = centerY - (distY * flare.position);
  12616. var cw = flare.size;
  12617. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12618. var cx = 2 * (x / globalViewport.width) - 1.0;
  12619. var cy = 1.0 - 2 * (y / globalViewport.height);
  12620. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12621. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12622. this._effect.setTexture("textureSampler", flare.texture);
  12623. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12624. engine.draw(true, 0, 6);
  12625. }
  12626. engine.setDepthBuffer(true);
  12627. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12628. return true;
  12629. };
  12630. LensFlareSystem.prototype.dispose = function () {
  12631. if (this._vertexBuffer) {
  12632. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12633. this._vertexBuffer = null;
  12634. }
  12635. if (this._indexBuffer) {
  12636. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12637. this._indexBuffer = null;
  12638. }
  12639. while (this.lensFlares.length) {
  12640. this.lensFlares[0].dispose();
  12641. }
  12642. var index = this._scene.lensFlareSystems.indexOf(this);
  12643. this._scene.lensFlareSystems.splice(index, 1);
  12644. };
  12645. return LensFlareSystem;
  12646. })();
  12647. BABYLON.LensFlareSystem = LensFlareSystem;
  12648. })(BABYLON || (BABYLON = {}));
  12649. var BABYLON;
  12650. (function (BABYLON) {
  12651. var IntersectionInfo = (function () {
  12652. function IntersectionInfo(bu, bv, distance) {
  12653. this.bu = bu;
  12654. this.bv = bv;
  12655. this.distance = distance;
  12656. this.faceId = 0;
  12657. }
  12658. return IntersectionInfo;
  12659. })();
  12660. BABYLON.IntersectionInfo = IntersectionInfo;
  12661. var PickingInfo = (function () {
  12662. function PickingInfo() {
  12663. this.hit = false;
  12664. this.distance = 0;
  12665. this.pickedPoint = null;
  12666. this.pickedMesh = null;
  12667. this.bu = 0;
  12668. this.bv = 0;
  12669. this.faceId = -1;
  12670. }
  12671. PickingInfo.prototype.getNormal = function () {
  12672. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12673. return null;
  12674. }
  12675. var indices = this.pickedMesh.getIndices();
  12676. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12677. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12678. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12679. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12680. normal0 = normal0.scale(this.bu);
  12681. normal1 = normal1.scale(this.bv);
  12682. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12683. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12684. };
  12685. PickingInfo.prototype.getTextureCoordinates = function () {
  12686. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12687. return null;
  12688. }
  12689. var indices = this.pickedMesh.getIndices();
  12690. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12691. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12692. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12693. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12694. uv0 = uv0.scale(this.bu);
  12695. uv1 = uv1.scale(this.bv);
  12696. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12697. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12698. };
  12699. return PickingInfo;
  12700. })();
  12701. BABYLON.PickingInfo = PickingInfo;
  12702. })(BABYLON || (BABYLON = {}));
  12703. var BABYLON;
  12704. (function (BABYLON) {
  12705. var FilesInput = (function () {
  12706. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12707. this.engine = p_engine;
  12708. this.canvas = p_canvas;
  12709. this.currentScene = p_scene;
  12710. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12711. this.progressCallback = p_progressCallback;
  12712. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12713. this.textureLoadingCallback = p_textureLoadingCallback;
  12714. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12715. }
  12716. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12717. var _this = this;
  12718. if (p_elementToMonitor) {
  12719. this.elementToMonitor = p_elementToMonitor;
  12720. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12721. _this.drag(e);
  12722. }, false);
  12723. this.elementToMonitor.addEventListener("dragover", function (e) {
  12724. _this.drag(e);
  12725. }, false);
  12726. this.elementToMonitor.addEventListener("drop", function (e) {
  12727. _this.drop(e);
  12728. }, false);
  12729. }
  12730. };
  12731. FilesInput.prototype.renderFunction = function () {
  12732. if (this.additionnalRenderLoopLogicCallback) {
  12733. this.additionnalRenderLoopLogicCallback();
  12734. }
  12735. if (this.currentScene) {
  12736. if (this.textureLoadingCallback) {
  12737. var remaining = this.currentScene.getWaitingItemsCount();
  12738. if (remaining > 0) {
  12739. this.textureLoadingCallback(remaining);
  12740. }
  12741. }
  12742. this.currentScene.render();
  12743. }
  12744. };
  12745. FilesInput.prototype.drag = function (e) {
  12746. e.stopPropagation();
  12747. e.preventDefault();
  12748. };
  12749. FilesInput.prototype.drop = function (eventDrop) {
  12750. eventDrop.stopPropagation();
  12751. eventDrop.preventDefault();
  12752. this.loadFiles(eventDrop);
  12753. };
  12754. FilesInput.prototype.loadFiles = function (event) {
  12755. var _this = this;
  12756. var that = this;
  12757. if (this.startingProcessingFilesCallback)
  12758. this.startingProcessingFilesCallback();
  12759. var sceneFileToLoad;
  12760. var filesToLoad;
  12761. if (event && event.dataTransfer && event.dataTransfer.files) {
  12762. filesToLoad = event.dataTransfer.files;
  12763. }
  12764. if (event && event.target && event.target.files) {
  12765. filesToLoad = event.target.files;
  12766. }
  12767. if (filesToLoad && filesToLoad.length > 0) {
  12768. for (var i = 0; i < filesToLoad.length; i++) {
  12769. switch (filesToLoad[i].type) {
  12770. case "image/jpeg":
  12771. case "image/png":
  12772. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12773. break;
  12774. case "image/targa":
  12775. case "image/vnd.ms-dds":
  12776. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12777. break;
  12778. default:
  12779. 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) {
  12780. sceneFileToLoad = filesToLoad[i];
  12781. }
  12782. break;
  12783. }
  12784. }
  12785. if (sceneFileToLoad) {
  12786. if (this.currentScene) {
  12787. this.engine.stopRenderLoop();
  12788. this.currentScene.dispose();
  12789. }
  12790. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12791. that.currentScene = newScene;
  12792. that.currentScene.executeWhenReady(function () {
  12793. if (that.currentScene.activeCamera) {
  12794. that.currentScene.activeCamera.attachControl(that.canvas);
  12795. }
  12796. if (that.sceneLoadedCallback) {
  12797. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12798. }
  12799. that.engine.runRenderLoop(function () {
  12800. that.renderFunction();
  12801. });
  12802. });
  12803. }, function (progress) {
  12804. if (_this.progressCallback) {
  12805. _this.progressCallback(progress);
  12806. }
  12807. });
  12808. } else {
  12809. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12810. }
  12811. }
  12812. };
  12813. FilesInput.FilesTextures = new Array();
  12814. FilesInput.FilesToLoad = new Array();
  12815. return FilesInput;
  12816. })();
  12817. BABYLON.FilesInput = FilesInput;
  12818. })(BABYLON || (BABYLON = {}));
  12819. var BABYLON;
  12820. (function (BABYLON) {
  12821. var OimoJSPlugin = (function () {
  12822. function OimoJSPlugin() {
  12823. this._registeredMeshes = [];
  12824. /**
  12825. * Update the body position according to the mesh position
  12826. * @param mesh
  12827. */
  12828. this.updateBodyPosition = function (mesh) {
  12829. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12830. var registeredMesh = this._registeredMeshes[index];
  12831. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12832. var body = registeredMesh.body.body;
  12833. var center = mesh.getBoundingInfo().boundingBox.center;
  12834. body.setPosition(center.x, center.y, center.z);
  12835. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12836. return;
  12837. }
  12838. if (registeredMesh.mesh.parent === mesh) {
  12839. mesh.computeWorldMatrix(true);
  12840. registeredMesh.mesh.computeWorldMatrix(true);
  12841. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12842. var absoluteRotation = mesh.rotation;
  12843. body = registeredMesh.body.body;
  12844. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12845. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12846. return;
  12847. }
  12848. }
  12849. };
  12850. }
  12851. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12852. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12853. };
  12854. OimoJSPlugin.prototype.initialize = function (iterations) {
  12855. this._world = new OIMO.World();
  12856. this._world.clear();
  12857. };
  12858. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12859. this._world.gravity = gravity;
  12860. };
  12861. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12862. var body = null;
  12863. this.unregisterMesh(mesh);
  12864. mesh.computeWorldMatrix(true);
  12865. switch (impostor) {
  12866. case BABYLON.PhysicsEngine.SphereImpostor:
  12867. var bbox = mesh.getBoundingInfo().boundingBox;
  12868. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12869. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12870. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12871. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12872. var deltaPosition = mesh.position.subtract(bbox.center);
  12873. body = new OIMO.Body({
  12874. type: 'sphere',
  12875. size: [size],
  12876. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12877. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12878. move: options.mass != 0,
  12879. config: [options.mass, options.friction, options.restitution],
  12880. world: this._world
  12881. });
  12882. this._registeredMeshes.push({
  12883. mesh: mesh,
  12884. body: body,
  12885. delta: deltaPosition
  12886. });
  12887. break;
  12888. case BABYLON.PhysicsEngine.PlaneImpostor:
  12889. case BABYLON.PhysicsEngine.BoxImpostor:
  12890. bbox = mesh.getBoundingInfo().boundingBox;
  12891. var min = bbox.minimumWorld;
  12892. var max = bbox.maximumWorld;
  12893. var box = max.subtract(min);
  12894. var sizeX = this._checkWithEpsilon(box.x);
  12895. var sizeY = this._checkWithEpsilon(box.y);
  12896. var sizeZ = this._checkWithEpsilon(box.z);
  12897. var deltaPosition = mesh.position.subtract(bbox.center);
  12898. body = new OIMO.Body({
  12899. type: 'box',
  12900. size: [sizeX, sizeY, sizeZ],
  12901. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12902. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12903. move: options.mass != 0,
  12904. config: [options.mass, options.friction, options.restitution],
  12905. world: this._world
  12906. });
  12907. this._registeredMeshes.push({
  12908. mesh: mesh,
  12909. body: body,
  12910. delta: deltaPosition
  12911. });
  12912. break;
  12913. }
  12914. return body;
  12915. };
  12916. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12917. var types = [], sizes = [], positions = [], rotations = [];
  12918. var initialMesh = parts[0].mesh;
  12919. for (var index = 0; index < parts.length; index++) {
  12920. var part = parts[index];
  12921. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12922. types.push(bodyParameters.type);
  12923. sizes.push.apply(sizes, bodyParameters.size);
  12924. positions.push.apply(positions, bodyParameters.pos);
  12925. rotations.push.apply(rotations, bodyParameters.rot);
  12926. }
  12927. var body = new OIMO.Body({
  12928. type: types,
  12929. size: sizes,
  12930. pos: positions,
  12931. rot: rotations,
  12932. move: options.mass != 0,
  12933. config: [options.mass, options.friction, options.restitution],
  12934. world: this._world
  12935. });
  12936. this._registeredMeshes.push({
  12937. mesh: initialMesh,
  12938. body: body
  12939. });
  12940. return body;
  12941. };
  12942. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12943. var bodyParameters = null;
  12944. var mesh = part.mesh;
  12945. switch (part.impostor) {
  12946. case BABYLON.PhysicsEngine.SphereImpostor:
  12947. var bbox = mesh.getBoundingInfo().boundingBox;
  12948. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12949. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12950. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12951. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12952. bodyParameters = {
  12953. type: 'sphere',
  12954. /* bug with oimo : sphere needs 3 sizes in this case */
  12955. size: [size, -1, -1],
  12956. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  12957. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12958. };
  12959. break;
  12960. case BABYLON.PhysicsEngine.PlaneImpostor:
  12961. case BABYLON.PhysicsEngine.BoxImpostor:
  12962. bbox = mesh.getBoundingInfo().boundingBox;
  12963. var min = bbox.minimumWorld;
  12964. var max = bbox.maximumWorld;
  12965. var box = max.subtract(min);
  12966. var sizeX = this._checkWithEpsilon(box.x);
  12967. var sizeY = this._checkWithEpsilon(box.y);
  12968. var sizeZ = this._checkWithEpsilon(box.z);
  12969. var relativePosition = mesh.position;
  12970. bodyParameters = {
  12971. type: 'box',
  12972. size: [sizeX, sizeY, sizeZ],
  12973. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  12974. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12975. };
  12976. break;
  12977. }
  12978. return bodyParameters;
  12979. };
  12980. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  12981. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12982. var registeredMesh = this._registeredMeshes[index];
  12983. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12984. if (registeredMesh.body) {
  12985. this._world.removeRigidBody(registeredMesh.body.body);
  12986. this._unbindBody(registeredMesh.body);
  12987. }
  12988. this._registeredMeshes.splice(index, 1);
  12989. return;
  12990. }
  12991. }
  12992. };
  12993. OimoJSPlugin.prototype._unbindBody = function (body) {
  12994. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12995. var registeredMesh = this._registeredMeshes[index];
  12996. if (registeredMesh.body === body) {
  12997. registeredMesh.body = null;
  12998. }
  12999. }
  13000. };
  13001. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13002. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13003. var registeredMesh = this._registeredMeshes[index];
  13004. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13005. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  13006. return;
  13007. }
  13008. }
  13009. };
  13010. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13011. var body1 = null, body2 = null;
  13012. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13013. var registeredMesh = this._registeredMeshes[index];
  13014. if (registeredMesh.mesh === mesh1) {
  13015. body1 = registeredMesh.body.body;
  13016. } else if (registeredMesh.mesh === mesh2) {
  13017. body2 = registeredMesh.body.body;
  13018. }
  13019. }
  13020. if (!body1 || !body2) {
  13021. return false;
  13022. }
  13023. if (!options) {
  13024. options = {};
  13025. }
  13026. new OIMO.Link({
  13027. type: options.type,
  13028. body1: body1,
  13029. body2: body2,
  13030. min: options.min,
  13031. max: options.max,
  13032. axe1: options.axe1,
  13033. axe2: options.axe2,
  13034. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13035. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13036. collision: options.collision,
  13037. spring: options.spring,
  13038. world: this._world
  13039. });
  13040. return true;
  13041. };
  13042. OimoJSPlugin.prototype.dispose = function () {
  13043. this._world.clear();
  13044. while (this._registeredMeshes.length) {
  13045. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13046. }
  13047. };
  13048. OimoJSPlugin.prototype.isSupported = function () {
  13049. return OIMO !== undefined;
  13050. };
  13051. OimoJSPlugin.prototype._getLastShape = function (body) {
  13052. var lastShape = body.shapes;
  13053. while (lastShape.next) {
  13054. lastShape = lastShape.next;
  13055. }
  13056. return lastShape;
  13057. };
  13058. OimoJSPlugin.prototype.runOneStep = function (time) {
  13059. this._world.step();
  13060. var i = this._registeredMeshes.length;
  13061. var m;
  13062. while (i--) {
  13063. var body = this._registeredMeshes[i].body.body;
  13064. var mesh = this._registeredMeshes[i].mesh;
  13065. var delta = this._registeredMeshes[i].delta;
  13066. if (!body.sleeping) {
  13067. if (body.shapes.next) {
  13068. var parentShape = this._getLastShape(body);
  13069. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13070. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13071. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13072. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13073. if (!mesh.rotationQuaternion) {
  13074. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13075. }
  13076. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13077. } else {
  13078. m = body.getMatrix();
  13079. mtx = BABYLON.Matrix.FromArray(m);
  13080. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13081. if (!delta) {
  13082. mesh.position.x = bodyX;
  13083. mesh.position.y = bodyY;
  13084. mesh.position.z = bodyZ;
  13085. } else {
  13086. mesh.position.x = bodyX + delta.x;
  13087. mesh.position.y = bodyY + delta.y;
  13088. mesh.position.z = bodyZ + delta.z;
  13089. }
  13090. if (!mesh.rotationQuaternion) {
  13091. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13092. }
  13093. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13094. }
  13095. }
  13096. }
  13097. };
  13098. return OimoJSPlugin;
  13099. })();
  13100. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13101. })(BABYLON || (BABYLON = {}));
  13102. var BABYLON;
  13103. (function (BABYLON) {
  13104. var PhysicsEngine = (function () {
  13105. function PhysicsEngine(plugin) {
  13106. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13107. }
  13108. PhysicsEngine.prototype._initialize = function (gravity) {
  13109. this._currentPlugin.initialize();
  13110. this._setGravity(gravity);
  13111. };
  13112. PhysicsEngine.prototype._runOneStep = function (delta) {
  13113. if (delta > 0.1) {
  13114. delta = 0.1;
  13115. } else if (delta <= 0) {
  13116. delta = 1.0 / 60.0;
  13117. }
  13118. this._currentPlugin.runOneStep(delta);
  13119. };
  13120. PhysicsEngine.prototype._setGravity = function (gravity) {
  13121. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13122. this._currentPlugin.setGravity(this.gravity);
  13123. };
  13124. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13125. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13126. };
  13127. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13128. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13129. };
  13130. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13131. this._currentPlugin.unregisterMesh(mesh);
  13132. };
  13133. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13134. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13135. };
  13136. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13137. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13138. };
  13139. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13140. this._currentPlugin.updateBodyPosition(mesh);
  13141. };
  13142. PhysicsEngine.prototype.dispose = function () {
  13143. this._currentPlugin.dispose();
  13144. };
  13145. PhysicsEngine.prototype.isSupported = function () {
  13146. return this._currentPlugin.isSupported();
  13147. };
  13148. PhysicsEngine.NoImpostor = 0;
  13149. PhysicsEngine.SphereImpostor = 1;
  13150. PhysicsEngine.BoxImpostor = 2;
  13151. PhysicsEngine.PlaneImpostor = 3;
  13152. PhysicsEngine.CompoundImpostor = 4;
  13153. PhysicsEngine.MeshImpostor = 4;
  13154. PhysicsEngine.CapsuleImpostor = 5;
  13155. PhysicsEngine.ConeImpostor = 6;
  13156. PhysicsEngine.CylinderImpostor = 7;
  13157. PhysicsEngine.ConvexHullImpostor = 8;
  13158. PhysicsEngine.Epsilon = 0.001;
  13159. return PhysicsEngine;
  13160. })();
  13161. BABYLON.PhysicsEngine = PhysicsEngine;
  13162. })(BABYLON || (BABYLON = {}));
  13163. var BABYLON;
  13164. (function (BABYLON) {
  13165. var serializeLight = function (light) {
  13166. var serializationObject = {};
  13167. serializationObject.name = light.name;
  13168. serializationObject.id = light.id;
  13169. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13170. if (light instanceof BABYLON.PointLight) {
  13171. serializationObject.type = 0;
  13172. serializationObject.position = light.position.asArray();
  13173. } else if (light instanceof BABYLON.DirectionalLight) {
  13174. serializationObject.type = 1;
  13175. var directionalLight = light;
  13176. serializationObject.position = directionalLight.position.asArray();
  13177. serializationObject.direction = directionalLight.direction.asArray();
  13178. } else if (light instanceof BABYLON.SpotLight) {
  13179. serializationObject.type = 2;
  13180. var spotLight = light;
  13181. serializationObject.position = spotLight.position.asArray();
  13182. serializationObject.direction = spotLight.position.asArray();
  13183. serializationObject.angle = spotLight.angle;
  13184. serializationObject.exponent = spotLight.exponent;
  13185. } else if (light instanceof BABYLON.HemisphericLight) {
  13186. serializationObject.type = 3;
  13187. var hemisphericLight = light;
  13188. serializationObject.direction = hemisphericLight.direction.asArray();
  13189. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13190. }
  13191. if (light.intensity) {
  13192. serializationObject.intensity = light.intensity;
  13193. }
  13194. serializationObject.range = light.range;
  13195. serializationObject.diffuse = light.diffuse.asArray();
  13196. serializationObject.specular = light.specular.asArray();
  13197. return serializationObject;
  13198. };
  13199. var serializeFresnelParameter = function (fresnelParameter) {
  13200. var serializationObject = {};
  13201. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13202. serializationObject.leftColor = fresnelParameter.leftColor;
  13203. serializationObject.rightColor = fresnelParameter.rightColor;
  13204. serializationObject.bias = fresnelParameter.bias;
  13205. serializationObject.power = fresnelParameter.power;
  13206. return serializationObject;
  13207. };
  13208. var serializeCamera = function (camera) {
  13209. var serializationObject = {};
  13210. serializationObject.name = camera.name;
  13211. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13212. serializationObject.id = camera.id;
  13213. serializationObject.position = camera.position.asArray();
  13214. if (camera.parent) {
  13215. serializationObject.parentId = camera.parent.id;
  13216. }
  13217. serializationObject.rotation = camera.rotation.asArray();
  13218. if (camera.lockedTarget && camera.lockedTarget.id) {
  13219. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13220. }
  13221. serializationObject.fov = camera.fov;
  13222. serializationObject.minZ = camera.minZ;
  13223. serializationObject.maxZ = camera.maxZ;
  13224. serializationObject.speed = camera.speed;
  13225. serializationObject.inertia = camera.inertia;
  13226. serializationObject.checkCollisions = camera.checkCollisions;
  13227. serializationObject.applyGravity = camera.applyGravity;
  13228. if (camera.ellipsoid) {
  13229. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13230. }
  13231. appendAnimations(camera, serializationObject);
  13232. serializationObject.layerMask = camera.layerMask;
  13233. return serializationObject;
  13234. };
  13235. var appendAnimations = function (source, destination) {
  13236. if (source.animations) {
  13237. destination.animations = [];
  13238. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13239. var animation = source.animations[animationIndex];
  13240. destination.animations.push(serializeAnimation(animation));
  13241. }
  13242. }
  13243. };
  13244. var serializeAnimation = function (animation) {
  13245. var serializationObject = {};
  13246. serializationObject.name = animation.name;
  13247. serializationObject.property = animation.targetProperty;
  13248. serializationObject.framePerSecond = animation.framePerSecond;
  13249. serializationObject.dataType = animation.dataType;
  13250. serializationObject.loopBehavior = animation.loopMode;
  13251. var dataType = animation.dataType;
  13252. serializationObject.keys = [];
  13253. var keys = animation.getKeys();
  13254. for (var index = 0; index < keys.length; index++) {
  13255. var animationKey = keys[index];
  13256. var key = {};
  13257. key.frame = animationKey.frame;
  13258. switch (dataType) {
  13259. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13260. key.values = [animationKey.value];
  13261. break;
  13262. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13263. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13264. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13265. key.values = animationKey.value.asArray();
  13266. break;
  13267. }
  13268. serializationObject.keys.push(key);
  13269. }
  13270. return serializationObject;
  13271. };
  13272. var serializeMultiMaterial = function (material) {
  13273. var serializationObject = {};
  13274. serializationObject.name = material.name;
  13275. serializationObject.id = material.id;
  13276. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13277. serializationObject.materials = [];
  13278. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13279. var subMat = material.subMaterials[matIndex];
  13280. if (subMat) {
  13281. serializationObject.materials.push(subMat.id);
  13282. } else {
  13283. serializationObject.materials.push(null);
  13284. }
  13285. }
  13286. return serializationObject;
  13287. };
  13288. var serializeMaterial = function (material) {
  13289. var serializationObject = {};
  13290. serializationObject.name = material.name;
  13291. serializationObject.ambient = material.ambientColor.asArray();
  13292. serializationObject.diffuse = material.diffuseColor.asArray();
  13293. serializationObject.specular = material.specularColor.asArray();
  13294. serializationObject.specularPower = material.specularPower;
  13295. serializationObject.emissive = material.emissiveColor.asArray();
  13296. serializationObject.alpha = material.alpha;
  13297. serializationObject.id = material.id;
  13298. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13299. serializationObject.backFaceCulling = material.backFaceCulling;
  13300. if (material.diffuseTexture) {
  13301. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13302. }
  13303. if (material.diffuseFresnelParameters) {
  13304. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13305. }
  13306. if (material.ambientTexture) {
  13307. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13308. }
  13309. if (material.opacityTexture) {
  13310. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13311. }
  13312. if (material.opacityFresnelParameters) {
  13313. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13314. }
  13315. if (material.reflectionTexture) {
  13316. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13317. }
  13318. if (material.reflectionFresnelParameters) {
  13319. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13320. }
  13321. if (material.emissiveTexture) {
  13322. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13323. }
  13324. if (material.emissiveFresnelParameters) {
  13325. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13326. }
  13327. if (material.specularTexture) {
  13328. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13329. }
  13330. if (material.bumpTexture) {
  13331. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13332. }
  13333. return serializationObject;
  13334. };
  13335. var serializeTexture = function (texture) {
  13336. var serializationObject = {};
  13337. if (!texture.name) {
  13338. return null;
  13339. }
  13340. if (texture instanceof BABYLON.CubeTexture) {
  13341. serializationObject.name = texture.name;
  13342. serializationObject.hasAlpha = texture.hasAlpha;
  13343. serializationObject.level = texture.level;
  13344. serializationObject.coordinatesMode = texture.coordinatesMode;
  13345. return serializationObject;
  13346. }
  13347. if (texture instanceof BABYLON.MirrorTexture) {
  13348. var mirrorTexture = texture;
  13349. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13350. serializationObject.renderList = [];
  13351. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13352. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13353. }
  13354. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13355. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13356. var renderTargetTexture = texture;
  13357. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13358. serializationObject.renderList = [];
  13359. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13360. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13361. }
  13362. }
  13363. var regularTexture = texture;
  13364. serializationObject.name = texture.name;
  13365. serializationObject.hasAlpha = texture.hasAlpha;
  13366. serializationObject.level = texture.level;
  13367. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13368. serializationObject.coordinatesMode = texture.coordinatesMode;
  13369. serializationObject.uOffset = regularTexture.uOffset;
  13370. serializationObject.vOffset = regularTexture.vOffset;
  13371. serializationObject.uScale = regularTexture.uScale;
  13372. serializationObject.vScale = regularTexture.vScale;
  13373. serializationObject.uAng = regularTexture.uAng;
  13374. serializationObject.vAng = regularTexture.vAng;
  13375. serializationObject.wAng = regularTexture.wAng;
  13376. serializationObject.wrapU = texture.wrapU;
  13377. serializationObject.wrapV = texture.wrapV;
  13378. appendAnimations(texture, serializationObject);
  13379. return serializationObject;
  13380. };
  13381. var serializeSkeleton = function (skeleton) {
  13382. var serializationObject = {};
  13383. serializationObject.name = skeleton.name;
  13384. serializationObject.id = skeleton.id;
  13385. serializationObject.bones = [];
  13386. for (var index = 0; index < skeleton.bones.length; index++) {
  13387. var bone = skeleton.bones[index];
  13388. var serializedBone = {
  13389. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13390. name: bone.name,
  13391. matrix: bone.getLocalMatrix().toArray()
  13392. };
  13393. serializationObject.bones.push(serializedBone);
  13394. if (bone.animations && bone.animations.length > 0) {
  13395. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13396. }
  13397. }
  13398. return serializationObject;
  13399. };
  13400. var serializeParticleSystem = function (particleSystem) {
  13401. var serializationObject = {};
  13402. serializationObject.emitterId = particleSystem.emitter.id;
  13403. serializationObject.capacity = particleSystem.getCapacity();
  13404. if (particleSystem.particleTexture) {
  13405. serializationObject.textureName = particleSystem.particleTexture.name;
  13406. }
  13407. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13408. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13409. serializationObject.minSize = particleSystem.minSize;
  13410. serializationObject.maxSize = particleSystem.maxSize;
  13411. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13412. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13413. serializationObject.emitRate = particleSystem.emitRate;
  13414. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13415. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13416. serializationObject.gravity = particleSystem.gravity.asArray();
  13417. serializationObject.direction1 = particleSystem.direction1.asArray();
  13418. serializationObject.direction2 = particleSystem.direction2.asArray();
  13419. serializationObject.color1 = particleSystem.color1.asArray();
  13420. serializationObject.color2 = particleSystem.color2.asArray();
  13421. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13422. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13423. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13424. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13425. serializationObject.blendMode = particleSystem.blendMode;
  13426. return serializationObject;
  13427. };
  13428. var serializeLensFlareSystem = function (lensFlareSystem) {
  13429. var serializationObject = {};
  13430. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13431. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13432. serializationObject.flares = [];
  13433. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13434. var flare = lensFlareSystem.lensFlares[index];
  13435. serializationObject.flares.push({
  13436. size: flare.size,
  13437. position: flare.position,
  13438. color: flare.color.asArray(),
  13439. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13440. });
  13441. }
  13442. return serializationObject;
  13443. };
  13444. var serializeShadowGenerator = function (light) {
  13445. var serializationObject = {};
  13446. var shadowGenerator = light.getShadowGenerator();
  13447. serializationObject.lightId = light.id;
  13448. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13449. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13450. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13451. serializationObject.renderList = [];
  13452. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13453. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13454. serializationObject.renderList.push(mesh.id);
  13455. }
  13456. return serializationObject;
  13457. };
  13458. var serializedGeometries = [];
  13459. var serializeGeometry = function (geometry, serializationGeometries) {
  13460. if (serializedGeometries[geometry.id]) {
  13461. return;
  13462. }
  13463. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13464. serializationGeometries.boxes.push(serializeBox(geometry));
  13465. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13466. serializationGeometries.spheres.push(serializeSphere(geometry));
  13467. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13468. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13469. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13470. serializationGeometries.toruses.push(serializeTorus(geometry));
  13471. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13472. serializationGeometries.grounds.push(serializeGround(geometry));
  13473. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13474. serializationGeometries.planes.push(serializePlane(geometry));
  13475. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13476. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13477. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13478. throw new Error("Unknow primitive type");
  13479. } else {
  13480. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13481. }
  13482. serializedGeometries[geometry.id] = true;
  13483. };
  13484. var serializeGeometryBase = function (geometry) {
  13485. var serializationObject = {};
  13486. serializationObject.id = geometry.id;
  13487. if (BABYLON.Tags.HasTags(geometry)) {
  13488. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13489. }
  13490. return serializationObject;
  13491. };
  13492. var serializeVertexData = function (vertexData) {
  13493. var serializationObject = serializeGeometryBase(vertexData);
  13494. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13495. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13496. }
  13497. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13498. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13499. }
  13500. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13501. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13502. }
  13503. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13504. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13505. }
  13506. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13507. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13508. }
  13509. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13510. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13511. serializationObject.matricesIndices._isExpanded = true;
  13512. }
  13513. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13514. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13515. }
  13516. serializationObject.indices = vertexData.getIndices();
  13517. return serializationObject;
  13518. };
  13519. var serializePrimitive = function (primitive) {
  13520. var serializationObject = serializeGeometryBase(primitive);
  13521. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13522. return serializationObject;
  13523. };
  13524. var serializeBox = function (box) {
  13525. var serializationObject = serializePrimitive(box);
  13526. serializationObject.size = box.size;
  13527. return serializationObject;
  13528. };
  13529. var serializeSphere = function (sphere) {
  13530. var serializationObject = serializePrimitive(sphere);
  13531. serializationObject.segments = sphere.segments;
  13532. serializationObject.diameter = sphere.diameter;
  13533. return serializationObject;
  13534. };
  13535. var serializeCylinder = function (cylinder) {
  13536. var serializationObject = serializePrimitive(cylinder);
  13537. serializationObject.height = cylinder.height;
  13538. serializationObject.diameterTop = cylinder.diameterTop;
  13539. serializationObject.diameterBottom = cylinder.diameterBottom;
  13540. serializationObject.tessellation = cylinder.tessellation;
  13541. return serializationObject;
  13542. };
  13543. var serializeTorus = function (torus) {
  13544. var serializationObject = serializePrimitive(torus);
  13545. serializationObject.diameter = torus.diameter;
  13546. serializationObject.thickness = torus.thickness;
  13547. serializationObject.tessellation = torus.tessellation;
  13548. return serializationObject;
  13549. };
  13550. var serializeGround = function (ground) {
  13551. var serializationObject = serializePrimitive(ground);
  13552. serializationObject.width = ground.width;
  13553. serializationObject.height = ground.height;
  13554. serializationObject.subdivisions = ground.subdivisions;
  13555. return serializationObject;
  13556. };
  13557. var serializePlane = function (plane) {
  13558. var serializationObject = serializePrimitive(plane);
  13559. serializationObject.size = plane.size;
  13560. return serializationObject;
  13561. };
  13562. var serializeTorusKnot = function (torusKnot) {
  13563. var serializationObject = serializePrimitive(torusKnot);
  13564. serializationObject.radius = torusKnot.radius;
  13565. serializationObject.tube = torusKnot.tube;
  13566. serializationObject.radialSegments = torusKnot.radialSegments;
  13567. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13568. serializationObject.p = torusKnot.p;
  13569. serializationObject.q = torusKnot.q;
  13570. return serializationObject;
  13571. };
  13572. var serializeMesh = function (mesh, serializationScene) {
  13573. var serializationObject = {};
  13574. serializationObject.name = mesh.name;
  13575. serializationObject.id = mesh.id;
  13576. if (BABYLON.Tags.HasTags(mesh)) {
  13577. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13578. }
  13579. serializationObject.position = mesh.position.asArray();
  13580. if (mesh.rotationQuaternion) {
  13581. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13582. } else if (mesh.rotation) {
  13583. serializationObject.rotation = mesh.rotation.asArray();
  13584. }
  13585. serializationObject.scaling = mesh.scaling.asArray();
  13586. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13587. serializationObject.isEnabled = mesh.isEnabled();
  13588. serializationObject.isVisible = mesh.isVisible;
  13589. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13590. serializationObject.pickable = mesh.isPickable;
  13591. serializationObject.receiveShadows = mesh.receiveShadows;
  13592. serializationObject.billboardMode = mesh.billboardMode;
  13593. serializationObject.visibility = mesh.visibility;
  13594. serializationObject.checkCollisions = mesh.checkCollisions;
  13595. if (mesh.parent) {
  13596. serializationObject.parentId = mesh.parent.id;
  13597. }
  13598. var geometry = mesh._geometry;
  13599. if (geometry) {
  13600. var geometryId = geometry.id;
  13601. serializationObject.geometryId = geometryId;
  13602. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13603. serializeGeometry(geometry, serializationScene.geometries);
  13604. }
  13605. serializationObject.subMeshes = [];
  13606. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13607. var subMesh = mesh.subMeshes[subIndex];
  13608. serializationObject.subMeshes.push({
  13609. materialIndex: subMesh.materialIndex,
  13610. verticesStart: subMesh.verticesStart,
  13611. verticesCount: subMesh.verticesCount,
  13612. indexStart: subMesh.indexStart,
  13613. indexCount: subMesh.indexCount
  13614. });
  13615. }
  13616. }
  13617. if (mesh.material) {
  13618. serializationObject.materialId = mesh.material.id;
  13619. } else {
  13620. mesh.material = null;
  13621. }
  13622. if (mesh.skeleton) {
  13623. serializationObject.skeletonId = mesh.skeleton.id;
  13624. }
  13625. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13626. serializationObject.physicsMass = mesh.getPhysicsMass();
  13627. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13628. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13629. switch (mesh.getPhysicsImpostor()) {
  13630. case BABYLON.PhysicsEngine.BoxImpostor:
  13631. serializationObject.physicsImpostor = 1;
  13632. break;
  13633. case BABYLON.PhysicsEngine.SphereImpostor:
  13634. serializationObject.physicsImpostor = 2;
  13635. break;
  13636. }
  13637. }
  13638. serializationObject.instances = [];
  13639. for (var index = 0; index < mesh.instances.length; index++) {
  13640. var instance = mesh.instances[index];
  13641. var serializationInstance = {
  13642. name: instance.name,
  13643. position: instance.position,
  13644. rotation: instance.rotation,
  13645. rotationQuaternion: instance.rotationQuaternion,
  13646. scaling: instance.scaling
  13647. };
  13648. serializationObject.instances.push(serializationInstance);
  13649. appendAnimations(instance, serializationInstance);
  13650. }
  13651. appendAnimations(mesh, serializationObject);
  13652. serializationObject.layerMask = mesh.layerMask;
  13653. return serializationObject;
  13654. };
  13655. var SceneSerializer = (function () {
  13656. function SceneSerializer() {
  13657. }
  13658. SceneSerializer.Serialize = function (scene) {
  13659. var serializationObject = {};
  13660. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13661. serializationObject.autoClear = scene.autoClear;
  13662. serializationObject.clearColor = scene.clearColor.asArray();
  13663. serializationObject.ambientColor = scene.ambientColor.asArray();
  13664. serializationObject.gravity = scene.gravity.asArray();
  13665. if (scene.fogMode && scene.fogMode !== 0) {
  13666. serializationObject.fogMode = scene.fogMode;
  13667. serializationObject.fogColor = scene.fogColor.asArray();
  13668. serializationObject.fogStart = scene.fogStart;
  13669. serializationObject.fogEnd = scene.fogEnd;
  13670. serializationObject.fogDensity = scene.fogDensity;
  13671. }
  13672. serializationObject.lights = [];
  13673. for (var index = 0; index < scene.lights.length; index++) {
  13674. var light = scene.lights[index];
  13675. serializationObject.lights.push(serializeLight(light));
  13676. }
  13677. serializationObject.cameras = [];
  13678. for (index = 0; index < scene.cameras.length; index++) {
  13679. var camera = scene.cameras[index];
  13680. if (camera instanceof BABYLON.FreeCamera) {
  13681. serializationObject.cameras.push(serializeCamera(camera));
  13682. }
  13683. }
  13684. if (scene.activeCamera) {
  13685. serializationObject.activeCameraID = scene.activeCamera.id;
  13686. }
  13687. serializationObject.materials = [];
  13688. serializationObject.multiMaterials = [];
  13689. for (index = 0; index < scene.materials.length; index++) {
  13690. var material = scene.materials[index];
  13691. if (material instanceof BABYLON.StandardMaterial) {
  13692. serializationObject.materials.push(serializeMaterial(material));
  13693. } else if (material instanceof BABYLON.MultiMaterial) {
  13694. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13695. }
  13696. }
  13697. serializationObject.skeletons = [];
  13698. for (index = 0; index < scene.skeletons.length; index++) {
  13699. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13700. }
  13701. serializationObject.geometries = {};
  13702. serializationObject.geometries.boxes = [];
  13703. serializationObject.geometries.spheres = [];
  13704. serializationObject.geometries.cylinders = [];
  13705. serializationObject.geometries.toruses = [];
  13706. serializationObject.geometries.grounds = [];
  13707. serializationObject.geometries.planes = [];
  13708. serializationObject.geometries.torusKnots = [];
  13709. serializationObject.geometries.vertexData = [];
  13710. serializedGeometries = [];
  13711. var geometries = scene.getGeometries();
  13712. for (var index = 0; index < geometries.length; index++) {
  13713. var geometry = geometries[index];
  13714. if (geometry.isReady()) {
  13715. serializeGeometry(geometry, serializationObject.geometries);
  13716. }
  13717. }
  13718. serializationObject.meshes = [];
  13719. for (index = 0; index < scene.meshes.length; index++) {
  13720. var abstractMesh = scene.meshes[index];
  13721. if (abstractMesh instanceof BABYLON.Mesh) {
  13722. var mesh = abstractMesh;
  13723. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13724. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13725. }
  13726. }
  13727. }
  13728. serializationObject.particleSystems = [];
  13729. for (index = 0; index < scene.particleSystems.length; index++) {
  13730. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13731. }
  13732. serializationObject.lensFlareSystems = [];
  13733. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13734. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13735. }
  13736. serializationObject.shadowGenerators = [];
  13737. for (index = 0; index < scene.lights.length; index++) {
  13738. light = scene.lights[index];
  13739. if (light.getShadowGenerator()) {
  13740. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13741. }
  13742. }
  13743. return serializationObject;
  13744. };
  13745. return SceneSerializer;
  13746. })();
  13747. BABYLON.SceneSerializer = SceneSerializer;
  13748. })(BABYLON || (BABYLON = {}));
  13749. var BABYLON;
  13750. (function (BABYLON) {
  13751. var SceneLoader = (function () {
  13752. function SceneLoader() {
  13753. }
  13754. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13755. get: function () {
  13756. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13757. },
  13758. set: function (value) {
  13759. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13760. },
  13761. enumerable: true,
  13762. configurable: true
  13763. });
  13764. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13765. get: function () {
  13766. return SceneLoader._ShowLoadingScreen;
  13767. },
  13768. set: function (value) {
  13769. SceneLoader._ShowLoadingScreen = value;
  13770. },
  13771. enumerable: true,
  13772. configurable: true
  13773. });
  13774. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13775. var dotPosition = sceneFilename.lastIndexOf(".");
  13776. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13777. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13778. var plugin = this._registeredPlugins[index];
  13779. if (plugin.extensions.indexOf(extension) !== -1) {
  13780. return plugin;
  13781. }
  13782. }
  13783. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13784. };
  13785. SceneLoader.RegisterPlugin = function (plugin) {
  13786. plugin.extensions = plugin.extensions.toLowerCase();
  13787. SceneLoader._registeredPlugins.push(plugin);
  13788. };
  13789. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13790. var _this = this;
  13791. var manifestChecked = function (success) {
  13792. scene.database = database;
  13793. var plugin = _this._getPluginForFilename(sceneFilename);
  13794. var importMeshFromData = function (data) {
  13795. var meshes = [];
  13796. var particleSystems = [];
  13797. var skeletons = [];
  13798. try {
  13799. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13800. if (onerror) {
  13801. onerror(scene);
  13802. }
  13803. return;
  13804. }
  13805. } catch (e) {
  13806. if (onerror) {
  13807. onerror(scene);
  13808. }
  13809. return;
  13810. }
  13811. if (onsuccess) {
  13812. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13813. onsuccess(meshes, particleSystems, skeletons);
  13814. }
  13815. };
  13816. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13817. importMeshFromData(sceneFilename.substr(5));
  13818. return;
  13819. }
  13820. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13821. importMeshFromData(data);
  13822. }, progressCallBack, database);
  13823. };
  13824. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13825. };
  13826. /**
  13827. * Load a scene
  13828. * @param rootUrl a string that defines the root url for scene and resources
  13829. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13830. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13831. */
  13832. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13833. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13834. };
  13835. /**
  13836. * Append a scene
  13837. * @param rootUrl a string that defines the root url for scene and resources
  13838. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13839. * @param scene is the instance of BABYLON.Scene to append to
  13840. */
  13841. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13842. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13843. var database;
  13844. if (SceneLoader.ShowLoadingScreen) {
  13845. scene.getEngine().displayLoadingUI();
  13846. }
  13847. var loadSceneFromData = function (data) {
  13848. scene.database = database;
  13849. if (!plugin.load(scene, data, rootUrl)) {
  13850. if (onerror) {
  13851. onerror(scene);
  13852. }
  13853. scene.getEngine().hideLoadingUI();
  13854. return;
  13855. }
  13856. if (onsuccess) {
  13857. onsuccess(scene);
  13858. }
  13859. if (SceneLoader.ShowLoadingScreen) {
  13860. scene.executeWhenReady(function () {
  13861. scene.getEngine().hideLoadingUI();
  13862. });
  13863. }
  13864. };
  13865. var manifestChecked = function (success) {
  13866. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13867. };
  13868. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13869. loadSceneFromData(sceneFilename.substr(5));
  13870. return;
  13871. }
  13872. if (rootUrl.indexOf("file:") === -1) {
  13873. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13874. } else {
  13875. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13876. }
  13877. };
  13878. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13879. SceneLoader._ShowLoadingScreen = true;
  13880. SceneLoader._registeredPlugins = new Array();
  13881. return SceneLoader;
  13882. })();
  13883. BABYLON.SceneLoader = SceneLoader;
  13884. ;
  13885. })(BABYLON || (BABYLON = {}));
  13886. var BABYLON;
  13887. (function (BABYLON) {
  13888. (function (Internals) {
  13889. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13890. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13891. texture.name = parsedTexture.name;
  13892. texture.hasAlpha = parsedTexture.hasAlpha;
  13893. texture.level = parsedTexture.level;
  13894. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13895. return texture;
  13896. };
  13897. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13898. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13899. return null;
  13900. }
  13901. if (parsedTexture.isCube) {
  13902. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13903. }
  13904. var texture;
  13905. if (parsedTexture.mirrorPlane) {
  13906. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13907. texture._waitingRenderList = parsedTexture.renderList;
  13908. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13909. } else if (parsedTexture.isRenderTarget) {
  13910. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13911. texture._waitingRenderList = parsedTexture.renderList;
  13912. } else {
  13913. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13914. }
  13915. texture.name = parsedTexture.name;
  13916. texture.hasAlpha = parsedTexture.hasAlpha;
  13917. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13918. texture.level = parsedTexture.level;
  13919. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13920. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13921. texture.uOffset = parsedTexture.uOffset;
  13922. texture.vOffset = parsedTexture.vOffset;
  13923. texture.uScale = parsedTexture.uScale;
  13924. texture.vScale = parsedTexture.vScale;
  13925. texture.uAng = parsedTexture.uAng;
  13926. texture.vAng = parsedTexture.vAng;
  13927. texture.wAng = parsedTexture.wAng;
  13928. texture.wrapU = parsedTexture.wrapU;
  13929. texture.wrapV = parsedTexture.wrapV;
  13930. if (parsedTexture.animations) {
  13931. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13932. var parsedAnimation = parsedTexture.animations[animationIndex];
  13933. texture.animations.push(parseAnimation(parsedAnimation));
  13934. }
  13935. }
  13936. return texture;
  13937. };
  13938. var parseSkeleton = function (parsedSkeleton, scene) {
  13939. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13940. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13941. var parsedBone = parsedSkeleton.bones[index];
  13942. var parentBone = null;
  13943. if (parsedBone.parentBoneIndex > -1) {
  13944. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13945. }
  13946. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13947. if (parsedBone.animation) {
  13948. bone.animations.push(parseAnimation(parsedBone.animation));
  13949. }
  13950. }
  13951. return skeleton;
  13952. };
  13953. var parseFresnelParameters = function (parsedFresnelParameters) {
  13954. var fresnelParameters = new BABYLON.FresnelParameters();
  13955. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  13956. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  13957. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  13958. fresnelParameters.bias = parsedFresnelParameters.bias;
  13959. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  13960. return fresnelParameters;
  13961. };
  13962. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  13963. var material;
  13964. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  13965. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  13966. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  13967. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  13968. material.specularPower = parsedMaterial.specularPower;
  13969. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  13970. material.alpha = parsedMaterial.alpha;
  13971. material.id = parsedMaterial.id;
  13972. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  13973. material.backFaceCulling = parsedMaterial.backFaceCulling;
  13974. material.wireframe = parsedMaterial.wireframe;
  13975. if (parsedMaterial.diffuseTexture) {
  13976. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  13977. }
  13978. if (parsedMaterial.diffuseFresnelParameters) {
  13979. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  13980. }
  13981. if (parsedMaterial.ambientTexture) {
  13982. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  13983. }
  13984. if (parsedMaterial.opacityTexture) {
  13985. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  13986. }
  13987. if (parsedMaterial.opacityFresnelParameters) {
  13988. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  13989. }
  13990. if (parsedMaterial.reflectionTexture) {
  13991. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  13992. }
  13993. if (parsedMaterial.reflectionFresnelParameters) {
  13994. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  13995. }
  13996. if (parsedMaterial.emissiveTexture) {
  13997. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  13998. }
  13999. if (parsedMaterial.emissiveFresnelParameters) {
  14000. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14001. }
  14002. if (parsedMaterial.specularTexture) {
  14003. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14004. }
  14005. if (parsedMaterial.bumpTexture) {
  14006. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14007. }
  14008. return material;
  14009. };
  14010. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14011. for (var index = 0; index < parsedData.materials.length; index++) {
  14012. var parsedMaterial = parsedData.materials[index];
  14013. if (parsedMaterial.id === id) {
  14014. return parseMaterial(parsedMaterial, scene, rootUrl);
  14015. }
  14016. }
  14017. return null;
  14018. };
  14019. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14020. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14021. multiMaterial.id = parsedMultiMaterial.id;
  14022. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14023. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14024. var subMatId = parsedMultiMaterial.materials[matIndex];
  14025. if (subMatId) {
  14026. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14027. } else {
  14028. multiMaterial.subMaterials.push(null);
  14029. }
  14030. }
  14031. return multiMaterial;
  14032. };
  14033. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14034. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14035. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14036. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14037. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14038. var parsedFlare = parsedLensFlareSystem.flares[index];
  14039. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14040. }
  14041. return lensFlareSystem;
  14042. };
  14043. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14044. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14045. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14046. if (parsedParticleSystem.textureName) {
  14047. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14048. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14049. }
  14050. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14051. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14052. particleSystem.minSize = parsedParticleSystem.minSize;
  14053. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14054. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14055. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14056. particleSystem.emitter = emitter;
  14057. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14058. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14059. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14060. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14061. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14062. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14063. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14064. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14065. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14066. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14067. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14068. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14069. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14070. particleSystem.start();
  14071. return particleSystem;
  14072. };
  14073. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14074. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14075. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14076. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14077. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14078. shadowGenerator.getShadowMap().renderList.push(mesh);
  14079. }
  14080. if (parsedShadowGenerator.usePoissonSampling) {
  14081. shadowGenerator.usePoissonSampling = true;
  14082. } else {
  14083. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14084. }
  14085. return shadowGenerator;
  14086. };
  14087. var parseAnimation = function (parsedAnimation) {
  14088. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14089. var dataType = parsedAnimation.dataType;
  14090. var keys = [];
  14091. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14092. var key = parsedAnimation.keys[index];
  14093. var data;
  14094. switch (dataType) {
  14095. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14096. data = key.values[0];
  14097. break;
  14098. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14099. data = BABYLON.Quaternion.FromArray(key.values);
  14100. break;
  14101. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14102. data = BABYLON.Matrix.FromArray(key.values);
  14103. break;
  14104. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14105. default:
  14106. data = BABYLON.Vector3.FromArray(key.values);
  14107. break;
  14108. }
  14109. keys.push({
  14110. frame: key.frame,
  14111. value: data
  14112. });
  14113. }
  14114. animation.setKeys(keys);
  14115. return animation;
  14116. };
  14117. var parseLight = function (parsedLight, scene) {
  14118. var light;
  14119. switch (parsedLight.type) {
  14120. case 0:
  14121. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14122. break;
  14123. case 1:
  14124. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14125. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14126. break;
  14127. case 2:
  14128. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14129. break;
  14130. case 3:
  14131. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14132. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14133. break;
  14134. }
  14135. light.id = parsedLight.id;
  14136. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14137. if (parsedLight.intensity !== undefined) {
  14138. light.intensity = parsedLight.intensity;
  14139. }
  14140. if (parsedLight.range) {
  14141. light.range = parsedLight.range;
  14142. }
  14143. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14144. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14145. if (parsedLight.excludedMeshesIds) {
  14146. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14147. }
  14148. if (parsedLight.includedOnlyMeshesIds) {
  14149. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14150. }
  14151. if (parsedLight.animations) {
  14152. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14153. var parsedAnimation = parsedLight.animations[animationIndex];
  14154. light.animations.push(parseAnimation(parsedAnimation));
  14155. }
  14156. }
  14157. if (parsedLight.autoAnimate) {
  14158. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14159. }
  14160. };
  14161. var parseCamera = function (parsedCamera, scene) {
  14162. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14163. camera.id = parsedCamera.id;
  14164. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14165. if (parsedCamera.parentId) {
  14166. camera._waitingParentId = parsedCamera.parentId;
  14167. }
  14168. if (parsedCamera.target) {
  14169. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14170. } else {
  14171. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14172. }
  14173. if (parsedCamera.lockedTargetId) {
  14174. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14175. }
  14176. camera.fov = parsedCamera.fov;
  14177. camera.minZ = parsedCamera.minZ;
  14178. camera.maxZ = parsedCamera.maxZ;
  14179. camera.speed = parsedCamera.speed;
  14180. camera.inertia = parsedCamera.inertia;
  14181. camera.checkCollisions = parsedCamera.checkCollisions;
  14182. camera.applyGravity = parsedCamera.applyGravity;
  14183. if (parsedCamera.ellipsoid) {
  14184. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14185. }
  14186. if (parsedCamera.animations) {
  14187. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14188. var parsedAnimation = parsedCamera.animations[animationIndex];
  14189. camera.animations.push(parseAnimation(parsedAnimation));
  14190. }
  14191. }
  14192. if (parsedCamera.autoAnimate) {
  14193. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14194. }
  14195. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14196. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14197. } else {
  14198. camera.layerMask = 0xFFFFFFFF;
  14199. }
  14200. return camera;
  14201. };
  14202. var parseGeometry = function (parsedGeometry, scene) {
  14203. var id = parsedGeometry.id;
  14204. return scene.getGeometryByID(id);
  14205. };
  14206. var parseBox = function (parsedBox, scene) {
  14207. if (parseGeometry(parsedBox, scene)) {
  14208. return null;
  14209. }
  14210. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14211. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14212. scene.pushGeometry(box, true);
  14213. return box;
  14214. };
  14215. var parseSphere = function (parsedSphere, scene) {
  14216. if (parseGeometry(parsedSphere, scene)) {
  14217. return null;
  14218. }
  14219. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14220. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14221. scene.pushGeometry(sphere, true);
  14222. return sphere;
  14223. };
  14224. var parseCylinder = function (parsedCylinder, scene) {
  14225. if (parseGeometry(parsedCylinder, scene)) {
  14226. return null;
  14227. }
  14228. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14229. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14230. scene.pushGeometry(cylinder, true);
  14231. return cylinder;
  14232. };
  14233. var parseTorus = function (parsedTorus, scene) {
  14234. if (parseGeometry(parsedTorus, scene)) {
  14235. return null;
  14236. }
  14237. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14238. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14239. scene.pushGeometry(torus, true);
  14240. return torus;
  14241. };
  14242. var parseGround = function (parsedGround, scene) {
  14243. if (parseGeometry(parsedGround, scene)) {
  14244. return null;
  14245. }
  14246. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14247. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14248. scene.pushGeometry(ground, true);
  14249. return ground;
  14250. };
  14251. var parsePlane = function (parsedPlane, scene) {
  14252. if (parseGeometry(parsedPlane, scene)) {
  14253. return null;
  14254. }
  14255. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14256. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14257. scene.pushGeometry(plane, true);
  14258. return plane;
  14259. };
  14260. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14261. if (parseGeometry(parsedTorusKnot, scene)) {
  14262. return null;
  14263. }
  14264. 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);
  14265. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14266. scene.pushGeometry(torusKnot, true);
  14267. return torusKnot;
  14268. };
  14269. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14270. if (parseGeometry(parsedVertexData, scene)) {
  14271. return null;
  14272. }
  14273. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14274. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14275. if (parsedVertexData.delayLoadingFile) {
  14276. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14277. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14278. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14279. geometry._delayInfo = [];
  14280. if (parsedVertexData.hasUVs) {
  14281. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14282. }
  14283. if (parsedVertexData.hasUVs2) {
  14284. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14285. }
  14286. if (parsedVertexData.hasColors) {
  14287. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14288. }
  14289. if (parsedVertexData.hasMatricesIndices) {
  14290. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14291. }
  14292. if (parsedVertexData.hasMatricesWeights) {
  14293. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14294. }
  14295. geometry._delayLoadingFunction = importVertexData;
  14296. } else {
  14297. importVertexData(parsedVertexData, geometry);
  14298. }
  14299. scene.pushGeometry(geometry, true);
  14300. return geometry;
  14301. };
  14302. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14303. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14304. mesh.id = parsedMesh.id;
  14305. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14306. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14307. if (parsedMesh.rotationQuaternion) {
  14308. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14309. } else if (parsedMesh.rotation) {
  14310. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14311. }
  14312. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14313. if (parsedMesh.localMatrix) {
  14314. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14315. } else if (parsedMesh.pivotMatrix) {
  14316. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14317. }
  14318. mesh.setEnabled(parsedMesh.isEnabled);
  14319. mesh.isVisible = parsedMesh.isVisible;
  14320. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14321. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14322. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14323. if (parsedMesh.pickable !== undefined) {
  14324. mesh.isPickable = parsedMesh.pickable;
  14325. }
  14326. mesh.receiveShadows = parsedMesh.receiveShadows;
  14327. mesh.billboardMode = parsedMesh.billboardMode;
  14328. if (parsedMesh.visibility !== undefined) {
  14329. mesh.visibility = parsedMesh.visibility;
  14330. }
  14331. mesh.checkCollisions = parsedMesh.checkCollisions;
  14332. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14333. if (parsedMesh.parentId) {
  14334. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14335. }
  14336. if (parsedMesh.delayLoadingFile) {
  14337. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14338. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14339. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14340. mesh._delayInfo = [];
  14341. if (parsedMesh.hasUVs) {
  14342. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14343. }
  14344. if (parsedMesh.hasUVs2) {
  14345. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14346. }
  14347. if (parsedMesh.hasColors) {
  14348. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14349. }
  14350. if (parsedMesh.hasMatricesIndices) {
  14351. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14352. }
  14353. if (parsedMesh.hasMatricesWeights) {
  14354. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14355. }
  14356. mesh._delayLoadingFunction = importGeometry;
  14357. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14358. mesh._checkDelayState();
  14359. }
  14360. } else {
  14361. importGeometry(parsedMesh, mesh);
  14362. }
  14363. if (parsedMesh.materialId) {
  14364. mesh.setMaterialByID(parsedMesh.materialId);
  14365. } else {
  14366. mesh.material = null;
  14367. }
  14368. if (parsedMesh.skeletonId > -1) {
  14369. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14370. }
  14371. if (parsedMesh.physicsImpostor) {
  14372. if (!scene.isPhysicsEnabled()) {
  14373. scene.enablePhysics();
  14374. }
  14375. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14376. }
  14377. if (parsedMesh.animations) {
  14378. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14379. var parsedAnimation = parsedMesh.animations[animationIndex];
  14380. mesh.animations.push(parseAnimation(parsedAnimation));
  14381. }
  14382. }
  14383. if (parsedMesh.autoAnimate) {
  14384. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14385. }
  14386. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14387. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14388. } else {
  14389. mesh.layerMask = 0xFFFFFFFF;
  14390. }
  14391. if (parsedMesh.instances) {
  14392. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14393. var parsedInstance = parsedMesh.instances[index];
  14394. var instance = mesh.createInstance(parsedInstance.name);
  14395. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14396. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14397. if (parsedInstance.rotationQuaternion) {
  14398. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14399. } else if (parsedInstance.rotation) {
  14400. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14401. }
  14402. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14403. instance.checkCollisions = mesh.checkCollisions;
  14404. if (parsedMesh.animations) {
  14405. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14406. parsedAnimation = parsedMesh.animations[animationIndex];
  14407. instance.animations.push(parseAnimation(parsedAnimation));
  14408. }
  14409. }
  14410. }
  14411. }
  14412. return mesh;
  14413. };
  14414. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14415. names = (names instanceof Array) ? names : [names];
  14416. for (var i in names) {
  14417. if (mesh.name === names[i]) {
  14418. hierarchyIds.push(mesh.id);
  14419. return true;
  14420. }
  14421. }
  14422. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14423. hierarchyIds.push(mesh.id);
  14424. return true;
  14425. }
  14426. return false;
  14427. };
  14428. var importVertexData = function (parsedVertexData, geometry) {
  14429. var vertexData = new BABYLON.VertexData();
  14430. var positions = parsedVertexData.positions;
  14431. if (positions) {
  14432. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14433. }
  14434. var normals = parsedVertexData.normals;
  14435. if (normals) {
  14436. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14437. }
  14438. var uvs = parsedVertexData.uvs;
  14439. if (uvs) {
  14440. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14441. }
  14442. var uv2s = parsedVertexData.uv2s;
  14443. if (uv2s) {
  14444. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14445. }
  14446. var colors = parsedVertexData.colors;
  14447. if (colors) {
  14448. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14449. }
  14450. var matricesIndices = parsedVertexData.matricesIndices;
  14451. if (matricesIndices) {
  14452. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14453. }
  14454. var matricesWeights = parsedVertexData.matricesWeights;
  14455. if (matricesWeights) {
  14456. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14457. }
  14458. var indices = parsedVertexData.indices;
  14459. if (indices) {
  14460. vertexData.indices = indices;
  14461. }
  14462. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14463. };
  14464. var importGeometry = function (parsedGeometry, mesh) {
  14465. var scene = mesh.getScene();
  14466. var geometryId = parsedGeometry.geometryId;
  14467. if (geometryId) {
  14468. var geometry = scene.getGeometryByID(geometryId);
  14469. if (geometry) {
  14470. geometry.applyToMesh(mesh);
  14471. }
  14472. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14473. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14474. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14475. if (parsedGeometry.uvs) {
  14476. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14477. }
  14478. if (parsedGeometry.uvs2) {
  14479. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14480. }
  14481. if (parsedGeometry.colors) {
  14482. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14483. }
  14484. if (parsedGeometry.matricesIndices) {
  14485. if (!parsedGeometry.matricesIndices._isExpanded) {
  14486. var floatIndices = [];
  14487. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14488. var matricesIndex = parsedGeometry.matricesIndices[i];
  14489. floatIndices.push(matricesIndex & 0x000000FF);
  14490. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14491. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14492. floatIndices.push(matricesIndex >> 24);
  14493. }
  14494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14495. } else {
  14496. delete parsedGeometry.matricesIndices._isExpanded;
  14497. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14498. }
  14499. }
  14500. if (parsedGeometry.matricesWeights) {
  14501. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14502. }
  14503. mesh.setIndices(parsedGeometry.indices);
  14504. }
  14505. if (parsedGeometry.subMeshes) {
  14506. mesh.subMeshes = [];
  14507. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14508. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14509. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14510. }
  14511. }
  14512. if (mesh._shouldGenerateFlatShading) {
  14513. mesh.convertToFlatShadedMesh();
  14514. delete mesh._shouldGenerateFlatShading;
  14515. }
  14516. mesh.computeWorldMatrix(true);
  14517. if (scene._selectionOctree) {
  14518. scene._selectionOctree.addMesh(mesh);
  14519. }
  14520. };
  14521. BABYLON.SceneLoader.RegisterPlugin({
  14522. extensions: ".babylon",
  14523. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14524. var parsedData = JSON.parse(data);
  14525. var loadedSkeletonsIds = [];
  14526. var loadedMaterialsIds = [];
  14527. var hierarchyIds = [];
  14528. for (var index = 0; index < parsedData.meshes.length; index++) {
  14529. var parsedMesh = parsedData.meshes[index];
  14530. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14531. if (meshesNames instanceof Array) {
  14532. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14533. }
  14534. if (parsedMesh.materialId) {
  14535. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14536. if (!materialFound) {
  14537. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14538. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14539. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14540. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14541. var subMatId = parsedMultiMaterial.materials[matIndex];
  14542. loadedMaterialsIds.push(subMatId);
  14543. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14544. }
  14545. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14546. parseMultiMaterial(parsedMultiMaterial, scene);
  14547. materialFound = true;
  14548. break;
  14549. }
  14550. }
  14551. }
  14552. if (!materialFound) {
  14553. loadedMaterialsIds.push(parsedMesh.materialId);
  14554. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14555. }
  14556. }
  14557. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14558. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14559. if (!skeletonAlreadyLoaded) {
  14560. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14561. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14562. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14563. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14564. loadedSkeletonsIds.push(parsedSkeleton.id);
  14565. }
  14566. }
  14567. }
  14568. }
  14569. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14570. meshes.push(mesh);
  14571. }
  14572. }
  14573. if (parsedData.particleSystems) {
  14574. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14575. var parsedParticleSystem = parsedData.particleSystems[index];
  14576. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14577. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14578. }
  14579. }
  14580. }
  14581. return true;
  14582. },
  14583. load: function (scene, data, rootUrl) {
  14584. var parsedData = JSON.parse(data);
  14585. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14586. scene.autoClear = parsedData.autoClear;
  14587. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14588. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14589. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14590. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14591. scene.fogMode = parsedData.fogMode;
  14592. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14593. scene.fogStart = parsedData.fogStart;
  14594. scene.fogEnd = parsedData.fogEnd;
  14595. scene.fogDensity = parsedData.fogDensity;
  14596. }
  14597. for (var index = 0; index < parsedData.lights.length; index++) {
  14598. var parsedLight = parsedData.lights[index];
  14599. parseLight(parsedLight, scene);
  14600. }
  14601. for (index = 0; index < parsedData.cameras.length; index++) {
  14602. var parsedCamera = parsedData.cameras[index];
  14603. parseCamera(parsedCamera, scene);
  14604. }
  14605. if (parsedData.activeCameraID) {
  14606. scene.setActiveCameraByID(parsedData.activeCameraID);
  14607. }
  14608. if (parsedData.materials) {
  14609. for (index = 0; index < parsedData.materials.length; index++) {
  14610. var parsedMaterial = parsedData.materials[index];
  14611. parseMaterial(parsedMaterial, scene, rootUrl);
  14612. }
  14613. }
  14614. if (parsedData.multiMaterials) {
  14615. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14616. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14617. parseMultiMaterial(parsedMultiMaterial, scene);
  14618. }
  14619. }
  14620. if (parsedData.skeletons) {
  14621. for (index = 0; index < parsedData.skeletons.length; index++) {
  14622. var parsedSkeleton = parsedData.skeletons[index];
  14623. parseSkeleton(parsedSkeleton, scene);
  14624. }
  14625. }
  14626. var geometries = parsedData.geometries;
  14627. if (geometries) {
  14628. var boxes = geometries.boxes;
  14629. if (boxes) {
  14630. for (index = 0; index < boxes.length; index++) {
  14631. var parsedBox = boxes[index];
  14632. parseBox(parsedBox, scene);
  14633. }
  14634. }
  14635. var spheres = geometries.spheres;
  14636. if (spheres) {
  14637. for (index = 0; index < spheres.length; index++) {
  14638. var parsedSphere = spheres[index];
  14639. parseSphere(parsedSphere, scene);
  14640. }
  14641. }
  14642. var cylinders = geometries.cylinders;
  14643. if (cylinders) {
  14644. for (index = 0; index < cylinders.length; index++) {
  14645. var parsedCylinder = cylinders[index];
  14646. parseCylinder(parsedCylinder, scene);
  14647. }
  14648. }
  14649. var toruses = geometries.toruses;
  14650. if (toruses) {
  14651. for (index = 0; index < toruses.length; index++) {
  14652. var parsedTorus = toruses[index];
  14653. parseTorus(parsedTorus, scene);
  14654. }
  14655. }
  14656. var grounds = geometries.grounds;
  14657. if (grounds) {
  14658. for (index = 0; index < grounds.length; index++) {
  14659. var parsedGround = grounds[index];
  14660. parseGround(parsedGround, scene);
  14661. }
  14662. }
  14663. var planes = geometries.planes;
  14664. if (planes) {
  14665. for (index = 0; index < planes.length; index++) {
  14666. var parsedPlane = planes[index];
  14667. parsePlane(parsedPlane, scene);
  14668. }
  14669. }
  14670. var torusKnots = geometries.torusKnots;
  14671. if (torusKnots) {
  14672. for (index = 0; index < torusKnots.length; index++) {
  14673. var parsedTorusKnot = torusKnots[index];
  14674. parseTorusKnot(parsedTorusKnot, scene);
  14675. }
  14676. }
  14677. var vertexData = geometries.vertexData;
  14678. if (vertexData) {
  14679. for (index = 0; index < vertexData.length; index++) {
  14680. var parsedVertexData = vertexData[index];
  14681. parseVertexData(parsedVertexData, scene, rootUrl);
  14682. }
  14683. }
  14684. }
  14685. for (index = 0; index < parsedData.meshes.length; index++) {
  14686. var parsedMesh = parsedData.meshes[index];
  14687. parseMesh(parsedMesh, scene, rootUrl);
  14688. }
  14689. for (index = 0; index < scene.cameras.length; index++) {
  14690. var camera = scene.cameras[index];
  14691. if (camera._waitingParentId) {
  14692. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14693. delete camera._waitingParentId;
  14694. }
  14695. if (camera instanceof BABYLON.FreeCamera) {
  14696. var freecamera = camera;
  14697. if (freecamera._waitingLockedTargetId) {
  14698. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14699. delete freecamera._waitingLockedTargetId;
  14700. }
  14701. }
  14702. }
  14703. if (parsedData.particleSystems) {
  14704. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14705. var parsedParticleSystem = parsedData.particleSystems[index];
  14706. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14707. }
  14708. }
  14709. if (parsedData.lensFlareSystems) {
  14710. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14711. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14712. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14713. }
  14714. }
  14715. if (parsedData.shadowGenerators) {
  14716. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14717. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14718. parseShadowGenerator(parsedShadowGenerator, scene);
  14719. }
  14720. }
  14721. return true;
  14722. }
  14723. });
  14724. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14725. var Internals = BABYLON.Internals;
  14726. })(BABYLON || (BABYLON = {}));
  14727. var BABYLON;
  14728. (function (BABYLON) {
  14729. var currentCSGMeshId = 0;
  14730. var Vertex = (function () {
  14731. function Vertex(pos, normal, uv) {
  14732. this.pos = pos;
  14733. this.normal = normal;
  14734. this.uv = uv;
  14735. }
  14736. Vertex.prototype.clone = function () {
  14737. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14738. };
  14739. Vertex.prototype.flip = function () {
  14740. this.normal = this.normal.scale(-1);
  14741. };
  14742. Vertex.prototype.interpolate = function (other, t) {
  14743. 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));
  14744. };
  14745. return Vertex;
  14746. })();
  14747. var Plane = (function () {
  14748. function Plane(normal, w) {
  14749. this.normal = normal;
  14750. this.w = w;
  14751. }
  14752. Plane.FromPoints = function (a, b, c) {
  14753. var v0 = c.subtract(a);
  14754. var v1 = b.subtract(a);
  14755. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14756. return null;
  14757. }
  14758. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14759. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14760. };
  14761. Plane.prototype.clone = function () {
  14762. return new Plane(this.normal.clone(), this.w);
  14763. };
  14764. Plane.prototype.flip = function () {
  14765. this.normal.scaleInPlace(-1);
  14766. this.w = -this.w;
  14767. };
  14768. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14769. var COPLANAR = 0;
  14770. var FRONT = 1;
  14771. var BACK = 2;
  14772. var SPANNING = 3;
  14773. var polygonType = 0;
  14774. var types = [];
  14775. for (var i = 0; i < polygon.vertices.length; i++) {
  14776. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14777. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14778. polygonType |= type;
  14779. types.push(type);
  14780. }
  14781. switch (polygonType) {
  14782. case COPLANAR:
  14783. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14784. break;
  14785. case FRONT:
  14786. front.push(polygon);
  14787. break;
  14788. case BACK:
  14789. back.push(polygon);
  14790. break;
  14791. case SPANNING:
  14792. var f = [], b = [];
  14793. for (i = 0; i < polygon.vertices.length; i++) {
  14794. var j = (i + 1) % polygon.vertices.length;
  14795. var ti = types[i], tj = types[j];
  14796. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14797. if (ti != BACK)
  14798. f.push(vi);
  14799. if (ti != FRONT)
  14800. b.push(ti != BACK ? vi.clone() : vi);
  14801. if ((ti | tj) == SPANNING) {
  14802. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14803. var v = vi.interpolate(vj, t);
  14804. f.push(v);
  14805. b.push(v.clone());
  14806. }
  14807. }
  14808. if (f.length >= 3) {
  14809. var poly = new Polygon(f, polygon.shared);
  14810. if (poly.plane)
  14811. front.push(poly);
  14812. }
  14813. if (b.length >= 3) {
  14814. poly = new Polygon(b, polygon.shared);
  14815. if (poly.plane)
  14816. back.push(poly);
  14817. }
  14818. break;
  14819. }
  14820. };
  14821. Plane.EPSILON = 1e-5;
  14822. return Plane;
  14823. })();
  14824. var Polygon = (function () {
  14825. function Polygon(vertices, shared) {
  14826. this.vertices = vertices;
  14827. this.shared = shared;
  14828. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14829. }
  14830. Polygon.prototype.clone = function () {
  14831. var vertices = this.vertices.map(function (v) {
  14832. return v.clone();
  14833. });
  14834. return new Polygon(vertices, this.shared);
  14835. };
  14836. Polygon.prototype.flip = function () {
  14837. this.vertices.reverse().map(function (v) {
  14838. v.flip();
  14839. });
  14840. this.plane.flip();
  14841. };
  14842. return Polygon;
  14843. })();
  14844. var Node = (function () {
  14845. function Node(polygons) {
  14846. this.plane = null;
  14847. this.front = null;
  14848. this.back = null;
  14849. this.polygons = [];
  14850. if (polygons) {
  14851. this.build(polygons);
  14852. }
  14853. }
  14854. Node.prototype.clone = function () {
  14855. var node = new Node();
  14856. node.plane = this.plane && this.plane.clone();
  14857. node.front = this.front && this.front.clone();
  14858. node.back = this.back && this.back.clone();
  14859. node.polygons = this.polygons.map(function (p) {
  14860. return p.clone();
  14861. });
  14862. return node;
  14863. };
  14864. Node.prototype.invert = function () {
  14865. for (var i = 0; i < this.polygons.length; i++) {
  14866. this.polygons[i].flip();
  14867. }
  14868. if (this.plane) {
  14869. this.plane.flip();
  14870. }
  14871. if (this.front) {
  14872. this.front.invert();
  14873. }
  14874. if (this.back) {
  14875. this.back.invert();
  14876. }
  14877. var temp = this.front;
  14878. this.front = this.back;
  14879. this.back = temp;
  14880. };
  14881. Node.prototype.clipPolygons = function (polygons) {
  14882. if (!this.plane)
  14883. return polygons.slice();
  14884. var front = [], back = [];
  14885. for (var i = 0; i < polygons.length; i++) {
  14886. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14887. }
  14888. if (this.front) {
  14889. front = this.front.clipPolygons(front);
  14890. }
  14891. if (this.back) {
  14892. back = this.back.clipPolygons(back);
  14893. } else {
  14894. back = [];
  14895. }
  14896. return front.concat(back);
  14897. };
  14898. Node.prototype.clipTo = function (bsp) {
  14899. this.polygons = bsp.clipPolygons(this.polygons);
  14900. if (this.front)
  14901. this.front.clipTo(bsp);
  14902. if (this.back)
  14903. this.back.clipTo(bsp);
  14904. };
  14905. Node.prototype.allPolygons = function () {
  14906. var polygons = this.polygons.slice();
  14907. if (this.front)
  14908. polygons = polygons.concat(this.front.allPolygons());
  14909. if (this.back)
  14910. polygons = polygons.concat(this.back.allPolygons());
  14911. return polygons;
  14912. };
  14913. Node.prototype.build = function (polygons) {
  14914. if (!polygons.length)
  14915. return;
  14916. if (!this.plane)
  14917. this.plane = polygons[0].plane.clone();
  14918. var front = [], back = [];
  14919. for (var i = 0; i < polygons.length; i++) {
  14920. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  14921. }
  14922. if (front.length) {
  14923. if (!this.front)
  14924. this.front = new Node();
  14925. this.front.build(front);
  14926. }
  14927. if (back.length) {
  14928. if (!this.back)
  14929. this.back = new Node();
  14930. this.back.build(back);
  14931. }
  14932. };
  14933. return Node;
  14934. })();
  14935. var CSG = (function () {
  14936. function CSG() {
  14937. this.polygons = new Array();
  14938. }
  14939. CSG.FromMesh = function (mesh) {
  14940. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  14941. if (mesh instanceof BABYLON.Mesh) {
  14942. mesh.computeWorldMatrix(true);
  14943. var matrix = mesh.getWorldMatrix();
  14944. var meshPosition = mesh.position.clone();
  14945. var meshRotation = mesh.rotation.clone();
  14946. var meshScaling = mesh.scaling.clone();
  14947. } else {
  14948. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  14949. }
  14950. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14951. var subMeshes = mesh.subMeshes;
  14952. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  14953. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  14954. vertices = [];
  14955. for (var j = 0; j < 3; j++) {
  14956. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  14957. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  14958. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  14959. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  14960. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  14961. vertex = new Vertex(position, normal, uv);
  14962. vertices.push(vertex);
  14963. }
  14964. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  14965. if (polygon.plane)
  14966. polygons.push(polygon);
  14967. }
  14968. }
  14969. var csg = CSG.FromPolygons(polygons);
  14970. csg.matrix = matrix;
  14971. csg.position = meshPosition;
  14972. csg.rotation = meshRotation;
  14973. csg.scaling = meshScaling;
  14974. currentCSGMeshId++;
  14975. return csg;
  14976. };
  14977. CSG.FromPolygons = function (polygons) {
  14978. var csg = new BABYLON.CSG();
  14979. csg.polygons = polygons;
  14980. return csg;
  14981. };
  14982. CSG.prototype.clone = function () {
  14983. var csg = new BABYLON.CSG();
  14984. csg.polygons = this.polygons.map(function (p) {
  14985. return p.clone();
  14986. });
  14987. csg.copyTransformAttributes(this);
  14988. return csg;
  14989. };
  14990. CSG.prototype.toPolygons = function () {
  14991. return this.polygons;
  14992. };
  14993. CSG.prototype.union = function (csg) {
  14994. var a = new Node(this.clone().polygons);
  14995. var b = new Node(csg.clone().polygons);
  14996. a.clipTo(b);
  14997. b.clipTo(a);
  14998. b.invert();
  14999. b.clipTo(a);
  15000. b.invert();
  15001. a.build(b.allPolygons());
  15002. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15003. };
  15004. CSG.prototype.unionInPlace = function (csg) {
  15005. var a = new Node(this.polygons);
  15006. var b = new Node(csg.polygons);
  15007. a.clipTo(b);
  15008. b.clipTo(a);
  15009. b.invert();
  15010. b.clipTo(a);
  15011. b.invert();
  15012. a.build(b.allPolygons());
  15013. this.polygons = a.allPolygons();
  15014. };
  15015. CSG.prototype.subtract = function (csg) {
  15016. var a = new Node(this.clone().polygons);
  15017. var b = new Node(csg.clone().polygons);
  15018. a.invert();
  15019. a.clipTo(b);
  15020. b.clipTo(a);
  15021. b.invert();
  15022. b.clipTo(a);
  15023. b.invert();
  15024. a.build(b.allPolygons());
  15025. a.invert();
  15026. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15027. };
  15028. CSG.prototype.subtractInPlace = function (csg) {
  15029. var a = new Node(this.polygons);
  15030. var b = new Node(csg.polygons);
  15031. a.invert();
  15032. a.clipTo(b);
  15033. b.clipTo(a);
  15034. b.invert();
  15035. b.clipTo(a);
  15036. b.invert();
  15037. a.build(b.allPolygons());
  15038. a.invert();
  15039. this.polygons = a.allPolygons();
  15040. };
  15041. CSG.prototype.intersect = function (csg) {
  15042. var a = new Node(this.clone().polygons);
  15043. var b = new Node(csg.clone().polygons);
  15044. a.invert();
  15045. b.clipTo(a);
  15046. b.invert();
  15047. a.clipTo(b);
  15048. b.clipTo(a);
  15049. a.build(b.allPolygons());
  15050. a.invert();
  15051. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15052. };
  15053. CSG.prototype.intersectInPlace = function (csg) {
  15054. var a = new Node(this.polygons);
  15055. var b = new Node(csg.polygons);
  15056. a.invert();
  15057. b.clipTo(a);
  15058. b.invert();
  15059. a.clipTo(b);
  15060. b.clipTo(a);
  15061. a.build(b.allPolygons());
  15062. a.invert();
  15063. this.polygons = a.allPolygons();
  15064. };
  15065. CSG.prototype.inverse = function () {
  15066. var csg = this.clone();
  15067. csg.inverseInPlace();
  15068. return csg;
  15069. };
  15070. CSG.prototype.inverseInPlace = function () {
  15071. this.polygons.map(function (p) {
  15072. p.flip();
  15073. });
  15074. };
  15075. CSG.prototype.copyTransformAttributes = function (csg) {
  15076. this.matrix = csg.matrix;
  15077. this.position = csg.position;
  15078. this.rotation = csg.rotation;
  15079. this.scaling = csg.scaling;
  15080. return this;
  15081. };
  15082. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15083. var matrix = this.matrix.clone();
  15084. matrix.invert();
  15085. 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;
  15086. if (keepSubMeshes) {
  15087. polygons.sort(function (a, b) {
  15088. if (a.shared.meshId === b.shared.meshId) {
  15089. return a.shared.subMeshId - b.shared.subMeshId;
  15090. } else {
  15091. return a.shared.meshId - b.shared.meshId;
  15092. }
  15093. });
  15094. }
  15095. for (var i = 0, il = polygons.length; i < il; i++) {
  15096. polygon = polygons[i];
  15097. if (!subMesh_dict[polygon.shared.meshId]) {
  15098. subMesh_dict[polygon.shared.meshId] = {};
  15099. }
  15100. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15101. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15102. indexStart: +Infinity,
  15103. indexEnd: -Infinity,
  15104. materialIndex: polygon.shared.materialIndex
  15105. };
  15106. }
  15107. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15108. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15109. polygonIndices[0] = 0;
  15110. polygonIndices[1] = j - 1;
  15111. polygonIndices[2] = j;
  15112. for (var k = 0; k < 3; k++) {
  15113. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15114. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15115. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15116. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15117. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15118. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15119. 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)) {
  15120. vertices.push(vertex.x, vertex.y, vertex.z);
  15121. uvs.push(uv.x, uv.y);
  15122. normals.push(normal.x, normal.y, normal.z);
  15123. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15124. }
  15125. indices.push(vertex_idx);
  15126. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15127. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15128. currentIndex++;
  15129. }
  15130. }
  15131. }
  15132. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15133. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15134. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15135. mesh.setIndices(indices);
  15136. if (keepSubMeshes) {
  15137. var materialIndexOffset = 0, materialMaxIndex;
  15138. mesh.subMeshes.length = 0;
  15139. for (var m in subMesh_dict) {
  15140. materialMaxIndex = -1;
  15141. for (var sm in subMesh_dict[m]) {
  15142. subMesh_obj = subMesh_dict[m][sm];
  15143. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15144. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15145. }
  15146. materialIndexOffset += ++materialMaxIndex;
  15147. }
  15148. }
  15149. return mesh;
  15150. };
  15151. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15152. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15153. mesh.material = material;
  15154. mesh.position.copyFrom(this.position);
  15155. mesh.rotation.copyFrom(this.rotation);
  15156. mesh.scaling.copyFrom(this.scaling);
  15157. mesh.computeWorldMatrix(true);
  15158. return mesh;
  15159. };
  15160. return CSG;
  15161. })();
  15162. BABYLON.CSG = CSG;
  15163. })(BABYLON || (BABYLON = {}));
  15164. var __extends = this.__extends || function (d, b) {
  15165. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15166. function __() { this.constructor = d; }
  15167. __.prototype = b.prototype;
  15168. d.prototype = new __();
  15169. };
  15170. var BABYLON;
  15171. (function (BABYLON) {
  15172. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15173. __extends(OculusDistortionCorrectionPostProcess, _super);
  15174. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15175. var _this = this;
  15176. _super.call(this, name, "oculusDistortionCorrection", [
  15177. 'LensCenter',
  15178. 'Scale',
  15179. 'ScaleIn',
  15180. 'HmdWarpParam'
  15181. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15182. this._isRightEye = isRightEye;
  15183. this._distortionFactors = cameraSettings.DistortionK;
  15184. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15185. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15186. this.onSizeChanged = function () {
  15187. _this.aspectRatio = _this.width * .5 / _this.height;
  15188. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15189. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15190. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15191. };
  15192. this.onApply = function (effect) {
  15193. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15194. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15195. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15196. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15197. };
  15198. }
  15199. return OculusDistortionCorrectionPostProcess;
  15200. })(BABYLON.PostProcess);
  15201. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15202. })(BABYLON || (BABYLON = {}));
  15203. var BABYLON;
  15204. (function (BABYLON) {
  15205. (function (JoystickAxis) {
  15206. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15207. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15208. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15209. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15210. var JoystickAxis = BABYLON.JoystickAxis;
  15211. var VirtualJoystick = (function () {
  15212. function VirtualJoystick(leftJoystick) {
  15213. var _this = this;
  15214. if (leftJoystick) {
  15215. this._leftJoystick = true;
  15216. } else {
  15217. this._leftJoystick = false;
  15218. }
  15219. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15220. VirtualJoystick._globalJoystickIndex++;
  15221. this._axisTargetedByLeftAndRight = 0 /* X */;
  15222. this._axisTargetedByUpAndDown = 1 /* Y */;
  15223. this.reverseLeftRight = false;
  15224. this.reverseUpDown = false;
  15225. this._touches = new BABYLON.VirtualJoystick.Collection();
  15226. this.deltaPosition = BABYLON.Vector3.Zero();
  15227. this._joystickSensibility = 25;
  15228. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15229. this._rotationSpeed = 25;
  15230. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15231. this._rotateOnAxisRelativeToMesh = false;
  15232. if (!VirtualJoystick.vjCanvas) {
  15233. window.addEventListener("resize", function () {
  15234. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15235. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15236. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15237. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15238. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15239. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15240. }, false);
  15241. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15242. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15243. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15244. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15245. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15246. VirtualJoystick.vjCanvas.style.width = "100%";
  15247. VirtualJoystick.vjCanvas.style.height = "100%";
  15248. VirtualJoystick.vjCanvas.style.position = "absolute";
  15249. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15250. VirtualJoystick.vjCanvas.style.top = "0px";
  15251. VirtualJoystick.vjCanvas.style.left = "0px";
  15252. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15253. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15254. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15255. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15256. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15257. document.body.appendChild(VirtualJoystick.vjCanvas);
  15258. }
  15259. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15260. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15261. this.pressed = false;
  15262. this._joystickColor = "cyan";
  15263. this._joystickPointerID = -1;
  15264. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15265. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15266. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15267. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15268. _this._onPointerDown(evt);
  15269. }, false);
  15270. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15271. _this._onPointerMove(evt);
  15272. }, false);
  15273. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15274. _this._onPointerUp(evt);
  15275. }, false);
  15276. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15277. _this._onPointerUp(evt);
  15278. }, false);
  15279. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15280. evt.preventDefault();
  15281. }, false);
  15282. requestAnimationFrame(function () {
  15283. _this._drawVirtualJoystick();
  15284. });
  15285. }
  15286. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15287. this._joystickSensibility = newJoystickSensibility;
  15288. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15289. };
  15290. VirtualJoystick.prototype._onPointerDown = function (e) {
  15291. var positionOnScreenCondition;
  15292. e.preventDefault();
  15293. if (this._leftJoystick === true) {
  15294. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15295. } else {
  15296. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15297. }
  15298. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15299. this._joystickPointerID = e.pointerId;
  15300. this._joystickPointerStartPos.x = e.clientX;
  15301. this._joystickPointerStartPos.y = e.clientY;
  15302. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15303. this._deltaJoystickVector.x = 0;
  15304. this._deltaJoystickVector.y = 0;
  15305. this.pressed = true;
  15306. this._touches.add(e.pointerId.toString(), e);
  15307. } else {
  15308. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15309. this._action();
  15310. this._touches.add(e.pointerId.toString(), e);
  15311. }
  15312. }
  15313. };
  15314. VirtualJoystick.prototype._onPointerMove = function (e) {
  15315. if (this._joystickPointerID == e.pointerId) {
  15316. this._joystickPointerPos.x = e.clientX;
  15317. this._joystickPointerPos.y = e.clientY;
  15318. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15319. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15320. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15321. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15322. switch (this._axisTargetedByLeftAndRight) {
  15323. case 0 /* X */:
  15324. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15325. break;
  15326. case 1 /* Y */:
  15327. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15328. break;
  15329. case 2 /* Z */:
  15330. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15331. break;
  15332. }
  15333. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15334. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15335. switch (this._axisTargetedByUpAndDown) {
  15336. case 0 /* X */:
  15337. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15338. break;
  15339. case 1 /* Y */:
  15340. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15341. break;
  15342. case 2 /* Z */:
  15343. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15344. break;
  15345. }
  15346. } else {
  15347. if (this._touches.item(e.pointerId.toString())) {
  15348. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15349. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15350. }
  15351. }
  15352. };
  15353. VirtualJoystick.prototype._onPointerUp = function (e) {
  15354. this._clearCanvas();
  15355. if (this._joystickPointerID == e.pointerId) {
  15356. this._joystickPointerID = -1;
  15357. this.pressed = false;
  15358. }
  15359. this._deltaJoystickVector.x = 0;
  15360. this._deltaJoystickVector.y = 0;
  15361. this._touches.remove(e.pointerId.toString());
  15362. };
  15363. /**
  15364. * Change the color of the virtual joystick
  15365. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15366. */
  15367. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15368. this._joystickColor = newColor;
  15369. };
  15370. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15371. this._action = action;
  15372. };
  15373. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15374. switch (axis) {
  15375. case 0 /* X */:
  15376. case 1 /* Y */:
  15377. case 2 /* Z */:
  15378. this._axisTargetedByLeftAndRight = axis;
  15379. break;
  15380. default:
  15381. this._axisTargetedByLeftAndRight = 0 /* X */;
  15382. break;
  15383. }
  15384. };
  15385. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15386. switch (axis) {
  15387. case 0 /* X */:
  15388. case 1 /* Y */:
  15389. case 2 /* Z */:
  15390. this._axisTargetedByUpAndDown = axis;
  15391. break;
  15392. default:
  15393. this._axisTargetedByUpAndDown = 1 /* Y */;
  15394. break;
  15395. }
  15396. };
  15397. VirtualJoystick.prototype._clearCanvas = function () {
  15398. if (this._leftJoystick) {
  15399. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15400. } else {
  15401. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15402. }
  15403. };
  15404. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15405. var _this = this;
  15406. if (this.pressed) {
  15407. this._clearCanvas();
  15408. this._touches.forEach(function (touch) {
  15409. if (touch.pointerId === _this._joystickPointerID) {
  15410. VirtualJoystick.vjCanvasContext.beginPath();
  15411. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15412. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15413. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15414. VirtualJoystick.vjCanvasContext.stroke();
  15415. VirtualJoystick.vjCanvasContext.beginPath();
  15416. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15417. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15418. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15419. VirtualJoystick.vjCanvasContext.stroke();
  15420. VirtualJoystick.vjCanvasContext.beginPath();
  15421. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15422. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15423. VirtualJoystick.vjCanvasContext.stroke();
  15424. } else {
  15425. VirtualJoystick.vjCanvasContext.beginPath();
  15426. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15427. VirtualJoystick.vjCanvasContext.beginPath();
  15428. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15429. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15430. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15431. VirtualJoystick.vjCanvasContext.stroke();
  15432. }
  15433. ;
  15434. });
  15435. }
  15436. requestAnimationFrame(function () {
  15437. _this._drawVirtualJoystick();
  15438. });
  15439. };
  15440. VirtualJoystick.prototype.releaseCanvas = function () {
  15441. if (VirtualJoystick.vjCanvas) {
  15442. document.body.removeChild(VirtualJoystick.vjCanvas);
  15443. VirtualJoystick.vjCanvas = null;
  15444. }
  15445. };
  15446. VirtualJoystick._globalJoystickIndex = 0;
  15447. return VirtualJoystick;
  15448. })();
  15449. BABYLON.VirtualJoystick = VirtualJoystick;
  15450. })(BABYLON || (BABYLON = {}));
  15451. var BABYLON;
  15452. (function (BABYLON) {
  15453. (function (VirtualJoystick) {
  15454. var Collection = (function () {
  15455. function Collection() {
  15456. this._count = 0;
  15457. this._collection = new Array();
  15458. }
  15459. Collection.prototype.Count = function () {
  15460. return this._count;
  15461. };
  15462. Collection.prototype.add = function (key, item) {
  15463. if (this._collection[key] != undefined) {
  15464. return undefined;
  15465. }
  15466. this._collection[key] = item;
  15467. return ++this._count;
  15468. };
  15469. Collection.prototype.remove = function (key) {
  15470. if (this._collection[key] == undefined) {
  15471. return undefined;
  15472. }
  15473. delete this._collection[key];
  15474. return --this._count;
  15475. };
  15476. Collection.prototype.item = function (key) {
  15477. return this._collection[key];
  15478. };
  15479. Collection.prototype.forEach = function (block) {
  15480. var key;
  15481. for (key in this._collection) {
  15482. if (this._collection.hasOwnProperty(key)) {
  15483. block(this._collection[key]);
  15484. }
  15485. }
  15486. };
  15487. return Collection;
  15488. })();
  15489. VirtualJoystick.Collection = Collection;
  15490. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15491. var VirtualJoystick = BABYLON.VirtualJoystick;
  15492. })(BABYLON || (BABYLON = {}));
  15493. var __extends = this.__extends || function (d, b) {
  15494. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15495. function __() { this.constructor = d; }
  15496. __.prototype = b.prototype;
  15497. d.prototype = new __();
  15498. };
  15499. var BABYLON;
  15500. (function (BABYLON) {
  15501. var OculusRiftDevKit2013_Metric = {
  15502. HResolution: 1280,
  15503. VResolution: 800,
  15504. HScreenSize: 0.149759993,
  15505. VScreenSize: 0.0935999975,
  15506. VScreenCenter: 0.0467999987,
  15507. EyeToScreenDistance: 0.0410000011,
  15508. LensSeparationDistance: 0.0635000020,
  15509. InterpupillaryDistance: 0.0640000030,
  15510. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15511. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15512. PostProcessScaleFactor: 1.714605507808412,
  15513. LensCenterOffset: 0.151976421
  15514. };
  15515. var _OculusInnerCamera = (function (_super) {
  15516. __extends(_OculusInnerCamera, _super);
  15517. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15518. _super.call(this, name, position, scene);
  15519. this._workMatrix = new BABYLON.Matrix();
  15520. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15521. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15522. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15523. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15524. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15525. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15526. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15527. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15528. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15529. }
  15530. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15531. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15532. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15533. return this._projectionMatrix;
  15534. };
  15535. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15536. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15537. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15538. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15539. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15540. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15541. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15542. return this._viewMatrix;
  15543. };
  15544. return _OculusInnerCamera;
  15545. })(BABYLON.FreeCamera);
  15546. var OculusCamera = (function (_super) {
  15547. __extends(OculusCamera, _super);
  15548. function OculusCamera(name, position, scene) {
  15549. _super.call(this, name, position, scene);
  15550. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15551. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15552. this.subCameras.push(this._leftCamera);
  15553. this.subCameras.push(this._rightCamera);
  15554. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15555. }
  15556. OculusCamera.prototype._update = function () {
  15557. this._leftCamera.position.copyFrom(this.position);
  15558. this._rightCamera.position.copyFrom(this.position);
  15559. this._updateCamera(this._leftCamera);
  15560. this._updateCamera(this._rightCamera);
  15561. _super.prototype._update.call(this);
  15562. };
  15563. OculusCamera.prototype._updateCamera = function (camera) {
  15564. camera.minZ = this.minZ;
  15565. camera.maxZ = this.maxZ;
  15566. camera.rotation.x = this.rotation.x;
  15567. camera.rotation.y = this.rotation.y;
  15568. camera.rotation.z = this.rotation.z;
  15569. };
  15570. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15571. var yaw = evt.alpha / 180 * Math.PI;
  15572. var pitch = evt.beta / 180 * Math.PI;
  15573. var roll = evt.gamma / 180 * Math.PI;
  15574. if (!this._offsetOrientation) {
  15575. this._offsetOrientation = {
  15576. yaw: yaw,
  15577. pitch: pitch,
  15578. roll: roll
  15579. };
  15580. return;
  15581. } else {
  15582. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15583. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15584. this.rotation.z += this._offsetOrientation.roll - roll;
  15585. this._offsetOrientation.yaw = yaw;
  15586. this._offsetOrientation.pitch = pitch;
  15587. this._offsetOrientation.roll = roll;
  15588. }
  15589. };
  15590. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15591. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15592. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15593. };
  15594. OculusCamera.prototype.detachControl = function (element) {
  15595. _super.prototype.detachControl.call(this, element);
  15596. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15597. };
  15598. return OculusCamera;
  15599. })(BABYLON.FreeCamera);
  15600. BABYLON.OculusCamera = OculusCamera;
  15601. })(BABYLON || (BABYLON = {}));
  15602. var __extends = this.__extends || function (d, b) {
  15603. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15604. function __() { this.constructor = d; }
  15605. __.prototype = b.prototype;
  15606. d.prototype = new __();
  15607. };
  15608. var BABYLON;
  15609. (function (BABYLON) {
  15610. var VirtualJoysticksCamera = (function (_super) {
  15611. __extends(VirtualJoysticksCamera, _super);
  15612. function VirtualJoysticksCamera(name, position, scene) {
  15613. _super.call(this, name, position, scene);
  15614. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15615. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15616. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15617. this._leftjoystick.setJoystickSensibility(0.15);
  15618. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15619. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15620. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15621. this._rightjoystick.reverseUpDown = true;
  15622. this._rightjoystick.setJoystickSensibility(0.05);
  15623. this._rightjoystick.setJoystickColor("yellow");
  15624. }
  15625. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15626. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15627. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15628. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15629. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15630. if (!this._leftjoystick.pressed) {
  15631. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15632. }
  15633. if (!this._rightjoystick.pressed) {
  15634. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15635. }
  15636. };
  15637. VirtualJoysticksCamera.prototype.dispose = function () {
  15638. this._leftjoystick.releaseCanvas();
  15639. _super.prototype.dispose.call(this);
  15640. };
  15641. return VirtualJoysticksCamera;
  15642. })(BABYLON.FreeCamera);
  15643. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15644. })(BABYLON || (BABYLON = {}));
  15645. var __extends = this.__extends || function (d, b) {
  15646. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15647. function __() { this.constructor = d; }
  15648. __.prototype = b.prototype;
  15649. d.prototype = new __();
  15650. };
  15651. var BABYLON;
  15652. (function (BABYLON) {
  15653. var ShaderMaterial = (function (_super) {
  15654. __extends(ShaderMaterial, _super);
  15655. function ShaderMaterial(name, scene, shaderPath, options) {
  15656. _super.call(this, name, scene);
  15657. this._textures = new Array();
  15658. this._floats = new Array();
  15659. this._floatsArrays = {};
  15660. this._colors3 = new Array();
  15661. this._colors4 = new Array();
  15662. this._vectors2 = new Array();
  15663. this._vectors3 = new Array();
  15664. this._matrices = new Array();
  15665. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15666. this._shaderPath = shaderPath;
  15667. options.needAlphaBlending = options.needAlphaBlending || false;
  15668. options.needAlphaTesting = options.needAlphaTesting || false;
  15669. options.attributes = options.attributes || ["position", "normal", "uv"];
  15670. options.uniforms = options.uniforms || ["worldViewProjection"];
  15671. options.samplers = options.samplers || [];
  15672. this._options = options;
  15673. }
  15674. ShaderMaterial.prototype.needAlphaBlending = function () {
  15675. return this._options.needAlphaBlending;
  15676. };
  15677. ShaderMaterial.prototype.needAlphaTesting = function () {
  15678. return this._options.needAlphaTesting;
  15679. };
  15680. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15681. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15682. this._options.uniforms.push(uniformName);
  15683. }
  15684. };
  15685. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15686. if (this._options.samplers.indexOf(name) === -1) {
  15687. this._options.samplers.push(name);
  15688. }
  15689. this._textures[name] = texture;
  15690. return this;
  15691. };
  15692. ShaderMaterial.prototype.setFloat = function (name, value) {
  15693. this._checkUniform(name);
  15694. this._floats[name] = value;
  15695. return this;
  15696. };
  15697. ShaderMaterial.prototype.setFloats = function (name, value) {
  15698. this._checkUniform(name);
  15699. this._floatsArrays[name] = value;
  15700. return this;
  15701. };
  15702. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15703. this._checkUniform(name);
  15704. this._colors3[name] = value;
  15705. return this;
  15706. };
  15707. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15708. this._checkUniform(name);
  15709. this._colors4[name] = value;
  15710. return this;
  15711. };
  15712. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15713. this._checkUniform(name);
  15714. this._vectors2[name] = value;
  15715. return this;
  15716. };
  15717. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15718. this._checkUniform(name);
  15719. this._vectors3[name] = value;
  15720. return this;
  15721. };
  15722. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15723. this._checkUniform(name);
  15724. this._matrices[name] = value;
  15725. return this;
  15726. };
  15727. ShaderMaterial.prototype.isReady = function () {
  15728. var engine = this.getScene().getEngine();
  15729. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15730. if (!this._effect.isReady()) {
  15731. return false;
  15732. }
  15733. return true;
  15734. };
  15735. ShaderMaterial.prototype.bind = function (world) {
  15736. if (this._options.uniforms.indexOf("world") !== -1) {
  15737. this._effect.setMatrix("world", world);
  15738. }
  15739. if (this._options.uniforms.indexOf("view") !== -1) {
  15740. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15741. }
  15742. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15743. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15744. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15745. }
  15746. if (this._options.uniforms.indexOf("projection") !== -1) {
  15747. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15748. }
  15749. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15750. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15751. }
  15752. for (var name in this._textures) {
  15753. this._effect.setTexture(name, this._textures[name]);
  15754. }
  15755. for (name in this._floats) {
  15756. this._effect.setFloat(name, this._floats[name]);
  15757. }
  15758. for (name in this._floatsArrays) {
  15759. this._effect.setArray(name, this._floatsArrays[name]);
  15760. }
  15761. for (name in this._colors3) {
  15762. this._effect.setColor3(name, this._colors3[name]);
  15763. }
  15764. for (name in this._colors4) {
  15765. var color = this._colors4[name];
  15766. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15767. }
  15768. for (name in this._vectors2) {
  15769. this._effect.setVector2(name, this._vectors2[name]);
  15770. }
  15771. for (name in this._vectors3) {
  15772. this._effect.setVector3(name, this._vectors3[name]);
  15773. }
  15774. for (name in this._matrices) {
  15775. this._effect.setMatrix(name, this._matrices[name]);
  15776. }
  15777. };
  15778. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15779. for (var name in this._textures) {
  15780. this._textures[name].dispose();
  15781. }
  15782. this._textures = [];
  15783. _super.prototype.dispose.call(this, forceDisposeEffect);
  15784. };
  15785. return ShaderMaterial;
  15786. })(BABYLON.Material);
  15787. BABYLON.ShaderMaterial = ShaderMaterial;
  15788. })(BABYLON || (BABYLON = {}));
  15789. var BABYLON;
  15790. (function (BABYLON) {
  15791. var VertexData = (function () {
  15792. function VertexData() {
  15793. }
  15794. VertexData.prototype.set = function (data, kind) {
  15795. switch (kind) {
  15796. case BABYLON.VertexBuffer.PositionKind:
  15797. this.positions = data;
  15798. break;
  15799. case BABYLON.VertexBuffer.NormalKind:
  15800. this.normals = data;
  15801. break;
  15802. case BABYLON.VertexBuffer.UVKind:
  15803. this.uvs = data;
  15804. break;
  15805. case BABYLON.VertexBuffer.UV2Kind:
  15806. this.uv2s = data;
  15807. break;
  15808. case BABYLON.VertexBuffer.ColorKind:
  15809. this.colors = data;
  15810. break;
  15811. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15812. this.matricesIndices = data;
  15813. break;
  15814. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15815. this.matricesWeights = data;
  15816. break;
  15817. }
  15818. };
  15819. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15820. this._applyTo(mesh, updatable);
  15821. };
  15822. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15823. this._applyTo(geometry, updatable);
  15824. };
  15825. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15826. this._update(mesh);
  15827. };
  15828. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15829. this._update(geometry);
  15830. };
  15831. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15832. if (this.positions) {
  15833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15834. }
  15835. if (this.normals) {
  15836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15837. }
  15838. if (this.uvs) {
  15839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15840. }
  15841. if (this.uv2s) {
  15842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15843. }
  15844. if (this.colors) {
  15845. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15846. }
  15847. if (this.matricesIndices) {
  15848. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15849. }
  15850. if (this.matricesWeights) {
  15851. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15852. }
  15853. if (this.indices) {
  15854. meshOrGeometry.setIndices(this.indices);
  15855. }
  15856. };
  15857. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15858. if (this.positions) {
  15859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15860. }
  15861. if (this.normals) {
  15862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15863. }
  15864. if (this.uvs) {
  15865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15866. }
  15867. if (this.uv2s) {
  15868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15869. }
  15870. if (this.colors) {
  15871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15872. }
  15873. if (this.matricesIndices) {
  15874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15875. }
  15876. if (this.matricesWeights) {
  15877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15878. }
  15879. if (this.indices) {
  15880. meshOrGeometry.setIndices(this.indices);
  15881. }
  15882. };
  15883. VertexData.prototype.transform = function (matrix) {
  15884. var transformed = BABYLON.Vector3.Zero();
  15885. if (this.positions) {
  15886. var position = BABYLON.Vector3.Zero();
  15887. for (var index = 0; index < this.positions.length; index += 3) {
  15888. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15889. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15890. this.positions[index] = transformed.x;
  15891. this.positions[index + 1] = transformed.y;
  15892. this.positions[index + 2] = transformed.z;
  15893. }
  15894. }
  15895. if (this.normals) {
  15896. var normal = BABYLON.Vector3.Zero();
  15897. for (index = 0; index < this.normals.length; index += 3) {
  15898. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  15899. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  15900. this.normals[index] = transformed.x;
  15901. this.normals[index + 1] = transformed.y;
  15902. this.normals[index + 2] = transformed.z;
  15903. }
  15904. }
  15905. };
  15906. VertexData.prototype.merge = function (other) {
  15907. if (other.indices) {
  15908. if (!this.indices) {
  15909. this.indices = [];
  15910. }
  15911. var offset = this.positions ? this.positions.length / 3 : 0;
  15912. for (var index = 0; index < other.indices.length; index++) {
  15913. this.indices.push(other.indices[index] + offset);
  15914. }
  15915. }
  15916. if (other.positions) {
  15917. if (!this.positions) {
  15918. this.positions = [];
  15919. }
  15920. for (index = 0; index < other.positions.length; index++) {
  15921. this.positions.push(other.positions[index]);
  15922. }
  15923. }
  15924. if (other.normals) {
  15925. if (!this.normals) {
  15926. this.normals = [];
  15927. }
  15928. for (index = 0; index < other.normals.length; index++) {
  15929. this.normals.push(other.normals[index]);
  15930. }
  15931. }
  15932. if (other.uvs) {
  15933. if (!this.uvs) {
  15934. this.uvs = [];
  15935. }
  15936. for (index = 0; index < other.uvs.length; index++) {
  15937. this.uvs.push(other.uvs[index]);
  15938. }
  15939. }
  15940. if (other.uv2s) {
  15941. if (!this.uv2s) {
  15942. this.uv2s = [];
  15943. }
  15944. for (index = 0; index < other.uv2s.length; index++) {
  15945. this.uv2s.push(other.uv2s[index]);
  15946. }
  15947. }
  15948. if (other.matricesIndices) {
  15949. if (!this.matricesIndices) {
  15950. this.matricesIndices = [];
  15951. }
  15952. for (index = 0; index < other.matricesIndices.length; index++) {
  15953. this.matricesIndices.push(other.matricesIndices[index]);
  15954. }
  15955. }
  15956. if (other.matricesWeights) {
  15957. if (!this.matricesWeights) {
  15958. this.matricesWeights = [];
  15959. }
  15960. for (index = 0; index < other.matricesWeights.length; index++) {
  15961. this.matricesWeights.push(other.matricesWeights[index]);
  15962. }
  15963. }
  15964. if (other.colors) {
  15965. if (!this.colors) {
  15966. this.colors = [];
  15967. }
  15968. for (index = 0; index < other.colors.length; index++) {
  15969. this.colors.push(other.colors[index]);
  15970. }
  15971. }
  15972. };
  15973. VertexData.ExtractFromMesh = function (mesh) {
  15974. return VertexData._ExtractFrom(mesh);
  15975. };
  15976. VertexData.ExtractFromGeometry = function (geometry) {
  15977. return VertexData._ExtractFrom(geometry);
  15978. };
  15979. VertexData._ExtractFrom = function (meshOrGeometry) {
  15980. var result = new BABYLON.VertexData();
  15981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15982. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15983. }
  15984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15985. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15986. }
  15987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15988. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15989. }
  15990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15991. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15992. }
  15993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15994. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15995. }
  15996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15997. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15998. }
  15999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16000. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16001. }
  16002. result.indices = meshOrGeometry.getIndices();
  16003. return result;
  16004. };
  16005. VertexData.CreateBox = function (size) {
  16006. var normalsSource = [
  16007. new BABYLON.Vector3(0, 0, 1),
  16008. new BABYLON.Vector3(0, 0, -1),
  16009. new BABYLON.Vector3(1, 0, 0),
  16010. new BABYLON.Vector3(-1, 0, 0),
  16011. new BABYLON.Vector3(0, 1, 0),
  16012. new BABYLON.Vector3(0, -1, 0)
  16013. ];
  16014. var indices = [];
  16015. var positions = [];
  16016. var normals = [];
  16017. var uvs = [];
  16018. size = size || 1;
  16019. for (var index = 0; index < normalsSource.length; index++) {
  16020. var normal = normalsSource[index];
  16021. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16022. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16023. var verticesLength = positions.length / 3;
  16024. indices.push(verticesLength);
  16025. indices.push(verticesLength + 1);
  16026. indices.push(verticesLength + 2);
  16027. indices.push(verticesLength);
  16028. indices.push(verticesLength + 2);
  16029. indices.push(verticesLength + 3);
  16030. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16031. positions.push(vertex.x, vertex.y, vertex.z);
  16032. normals.push(normal.x, normal.y, normal.z);
  16033. uvs.push(1.0, 1.0);
  16034. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16035. positions.push(vertex.x, vertex.y, vertex.z);
  16036. normals.push(normal.x, normal.y, normal.z);
  16037. uvs.push(0.0, 1.0);
  16038. vertex = normal.add(side1).add(side2).scale(size / 2);
  16039. positions.push(vertex.x, vertex.y, vertex.z);
  16040. normals.push(normal.x, normal.y, normal.z);
  16041. uvs.push(0.0, 0.0);
  16042. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16043. positions.push(vertex.x, vertex.y, vertex.z);
  16044. normals.push(normal.x, normal.y, normal.z);
  16045. uvs.push(1.0, 0.0);
  16046. }
  16047. var vertexData = new BABYLON.VertexData();
  16048. vertexData.indices = indices;
  16049. vertexData.positions = positions;
  16050. vertexData.normals = normals;
  16051. vertexData.uvs = uvs;
  16052. return vertexData;
  16053. };
  16054. VertexData.CreateSphere = function (segments, diameter) {
  16055. segments = segments || 32;
  16056. diameter = diameter || 1;
  16057. var radius = diameter / 2;
  16058. var totalZRotationSteps = 2 + segments;
  16059. var totalYRotationSteps = 2 * totalZRotationSteps;
  16060. var indices = [];
  16061. var positions = [];
  16062. var normals = [];
  16063. var uvs = [];
  16064. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16065. var normalizedZ = zRotationStep / totalZRotationSteps;
  16066. var angleZ = (normalizedZ * Math.PI);
  16067. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16068. var normalizedY = yRotationStep / totalYRotationSteps;
  16069. var angleY = normalizedY * Math.PI * 2;
  16070. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16071. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16072. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16073. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16074. var vertex = complete.scale(radius);
  16075. var normal = BABYLON.Vector3.Normalize(vertex);
  16076. positions.push(vertex.x, vertex.y, vertex.z);
  16077. normals.push(normal.x, normal.y, normal.z);
  16078. uvs.push(normalizedZ, normalizedY);
  16079. }
  16080. if (zRotationStep > 0) {
  16081. var verticesCount = positions.length / 3;
  16082. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16083. indices.push((firstIndex));
  16084. indices.push((firstIndex + 1));
  16085. indices.push(firstIndex + totalYRotationSteps + 1);
  16086. indices.push((firstIndex + totalYRotationSteps + 1));
  16087. indices.push((firstIndex + 1));
  16088. indices.push((firstIndex + totalYRotationSteps + 2));
  16089. }
  16090. }
  16091. }
  16092. var vertexData = new BABYLON.VertexData();
  16093. vertexData.indices = indices;
  16094. vertexData.positions = positions;
  16095. vertexData.normals = normals;
  16096. vertexData.uvs = uvs;
  16097. return vertexData;
  16098. };
  16099. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16100. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16101. var radiusTop = diameterTop / 2;
  16102. var radiusBottom = diameterBottom / 2;
  16103. var indices = [];
  16104. var positions = [];
  16105. var normals = [];
  16106. var uvs = [];
  16107. height = height || 1;
  16108. diameterTop = diameterTop || 0.5;
  16109. diameterBottom = diameterBottom || 1;
  16110. tessellation = tessellation || 16;
  16111. subdivisions = subdivisions || 1;
  16112. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16113. var getCircleVector = function (i) {
  16114. var angle = (i * 2.0 * Math.PI / tessellation);
  16115. var dx = Math.cos(angle);
  16116. var dz = Math.sin(angle);
  16117. return new BABYLON.Vector3(dx, 0, dz);
  16118. };
  16119. var createCylinderCap = function (isTop) {
  16120. var radius = isTop ? radiusTop : radiusBottom;
  16121. if (radius == 0) {
  16122. return;
  16123. }
  16124. var vbase = positions.length / 3;
  16125. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16126. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16127. if (!isTop) {
  16128. offset.scaleInPlace(-1);
  16129. textureScale.x = -textureScale.x;
  16130. }
  16131. for (i = 0; i < tessellation; i++) {
  16132. var circleVector = getCircleVector(i);
  16133. var position = circleVector.scale(radius).add(offset);
  16134. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16135. positions.push(position.x, position.y, position.z);
  16136. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16137. }
  16138. for (var i = 0; i < tessellation - 2; i++) {
  16139. if (!isTop) {
  16140. indices.push(vbase);
  16141. indices.push(vbase + (i + 2) % tessellation);
  16142. indices.push(vbase + (i + 1) % tessellation);
  16143. } else {
  16144. indices.push(vbase);
  16145. indices.push(vbase + (i + 1) % tessellation);
  16146. indices.push(vbase + (i + 2) % tessellation);
  16147. }
  16148. }
  16149. };
  16150. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16151. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16152. var stride = tessellation + 1;
  16153. for (var i = 0; i <= tessellation; i++) {
  16154. var circleVector = getCircleVector(i);
  16155. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16156. var position, radius = radiusBottom;
  16157. for (var s = 0; s <= subdivisions; s++) {
  16158. position = circleVector.scale(radius);
  16159. position.addInPlace(base.add(offset.scale(s)));
  16160. textureCoordinate.y += 1 / subdivisions;
  16161. radius += (radiusTop - radiusBottom) / subdivisions;
  16162. positions.push(position.x, position.y, position.z);
  16163. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16164. }
  16165. }
  16166. subdivisions += 1;
  16167. for (var s = 0; s < subdivisions - 1; s++) {
  16168. for (var i = 0; i <= tessellation; i++) {
  16169. indices.push(i * subdivisions + s);
  16170. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16171. indices.push(i * subdivisions + (s + 1));
  16172. indices.push(i * subdivisions + (s + 1));
  16173. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16174. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16175. }
  16176. }
  16177. createCylinderCap(true);
  16178. createCylinderCap(false);
  16179. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16180. var vertexData = new BABYLON.VertexData();
  16181. vertexData.indices = indices;
  16182. vertexData.positions = positions;
  16183. vertexData.normals = normals;
  16184. vertexData.uvs = uvs;
  16185. return vertexData;
  16186. };
  16187. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16188. var indices = [];
  16189. var positions = [];
  16190. var normals = [];
  16191. var uvs = [];
  16192. diameter = diameter || 1;
  16193. thickness = thickness || 0.5;
  16194. tessellation = tessellation || 16;
  16195. var stride = tessellation + 1;
  16196. for (var i = 0; i <= tessellation; i++) {
  16197. var u = i / tessellation;
  16198. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16199. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16200. for (var j = 0; j <= tessellation; j++) {
  16201. var v = 1 - j / tessellation;
  16202. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16203. var dx = Math.cos(innerAngle);
  16204. var dy = Math.sin(innerAngle);
  16205. var normal = new BABYLON.Vector3(dx, dy, 0);
  16206. var position = normal.scale(thickness / 2);
  16207. var textureCoordinate = new BABYLON.Vector2(u, v);
  16208. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16209. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16210. positions.push(position.x, position.y, position.z);
  16211. normals.push(normal.x, normal.y, normal.z);
  16212. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16213. var nextI = (i + 1) % stride;
  16214. var nextJ = (j + 1) % stride;
  16215. indices.push(i * stride + j);
  16216. indices.push(i * stride + nextJ);
  16217. indices.push(nextI * stride + j);
  16218. indices.push(i * stride + nextJ);
  16219. indices.push(nextI * stride + nextJ);
  16220. indices.push(nextI * stride + j);
  16221. }
  16222. }
  16223. var vertexData = new BABYLON.VertexData();
  16224. vertexData.indices = indices;
  16225. vertexData.positions = positions;
  16226. vertexData.normals = normals;
  16227. vertexData.uvs = uvs;
  16228. return vertexData;
  16229. };
  16230. VertexData.CreateLines = function (points) {
  16231. var indices = [];
  16232. var positions = [];
  16233. for (var index = 0; index < points.length; index++) {
  16234. positions.push(points[index].x, points[index].y, points[index].z);
  16235. if (index > 0) {
  16236. indices.push(index - 1);
  16237. indices.push(index);
  16238. }
  16239. }
  16240. var vertexData = new BABYLON.VertexData();
  16241. vertexData.indices = indices;
  16242. vertexData.positions = positions;
  16243. return vertexData;
  16244. };
  16245. VertexData.CreateGround = function (width, height, subdivisions) {
  16246. var indices = [];
  16247. var positions = [];
  16248. var normals = [];
  16249. var uvs = [];
  16250. var row, col;
  16251. width = width || 1;
  16252. height = height || 1;
  16253. subdivisions = subdivisions || 1;
  16254. for (row = 0; row <= subdivisions; row++) {
  16255. for (col = 0; col <= subdivisions; col++) {
  16256. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16257. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16258. positions.push(position.x, position.y, position.z);
  16259. normals.push(normal.x, normal.y, normal.z);
  16260. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16261. }
  16262. }
  16263. for (row = 0; row < subdivisions; row++) {
  16264. for (col = 0; col < subdivisions; col++) {
  16265. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16266. indices.push(col + 1 + row * (subdivisions + 1));
  16267. indices.push(col + row * (subdivisions + 1));
  16268. indices.push(col + (row + 1) * (subdivisions + 1));
  16269. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16270. indices.push(col + row * (subdivisions + 1));
  16271. }
  16272. }
  16273. var vertexData = new BABYLON.VertexData();
  16274. vertexData.indices = indices;
  16275. vertexData.positions = positions;
  16276. vertexData.normals = normals;
  16277. vertexData.uvs = uvs;
  16278. return vertexData;
  16279. };
  16280. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16281. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16282. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16283. var indices = [];
  16284. var positions = [];
  16285. var normals = [];
  16286. var uvs = [];
  16287. var row, col, tileRow, tileCol;
  16288. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16289. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16290. precision.w = (precision.w < 1) ? 1 : precision.w;
  16291. precision.h = (precision.h < 1) ? 1 : precision.h;
  16292. var tileSize = {
  16293. 'w': (xmax - xmin) / subdivisions.w,
  16294. 'h': (zmax - zmin) / subdivisions.h
  16295. };
  16296. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16297. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16298. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16299. }
  16300. }
  16301. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16302. var base = positions.length / 3;
  16303. var rowLength = precision.w + 1;
  16304. for (row = 0; row < precision.h; row++) {
  16305. for (col = 0; col < precision.w; col++) {
  16306. var square = [
  16307. base + col + row * rowLength,
  16308. base + (col + 1) + row * rowLength,
  16309. base + (col + 1) + (row + 1) * rowLength,
  16310. base + col + (row + 1) * rowLength
  16311. ];
  16312. indices.push(square[1]);
  16313. indices.push(square[2]);
  16314. indices.push(square[3]);
  16315. indices.push(square[0]);
  16316. indices.push(square[1]);
  16317. indices.push(square[3]);
  16318. }
  16319. }
  16320. var position = BABYLON.Vector3.Zero();
  16321. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16322. for (row = 0; row <= precision.h; row++) {
  16323. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16324. for (col = 0; col <= precision.w; col++) {
  16325. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16326. position.y = 0;
  16327. positions.push(position.x, position.y, position.z);
  16328. normals.push(normal.x, normal.y, normal.z);
  16329. uvs.push(col / precision.w, row / precision.h);
  16330. }
  16331. }
  16332. }
  16333. var vertexData = new BABYLON.VertexData();
  16334. vertexData.indices = indices;
  16335. vertexData.positions = positions;
  16336. vertexData.normals = normals;
  16337. vertexData.uvs = uvs;
  16338. return vertexData;
  16339. };
  16340. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16341. var indices = [];
  16342. var positions = [];
  16343. var normals = [];
  16344. var uvs = [];
  16345. var row, col;
  16346. for (row = 0; row <= subdivisions; row++) {
  16347. for (col = 0; col <= subdivisions; col++) {
  16348. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16349. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16350. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16351. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16352. var r = buffer[pos] / 255.0;
  16353. var g = buffer[pos + 1] / 255.0;
  16354. var b = buffer[pos + 2] / 255.0;
  16355. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16356. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16357. positions.push(position.x, position.y, position.z);
  16358. normals.push(0, 0, 0);
  16359. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16360. }
  16361. }
  16362. for (row = 0; row < subdivisions; row++) {
  16363. for (col = 0; col < subdivisions; col++) {
  16364. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16365. indices.push(col + 1 + row * (subdivisions + 1));
  16366. indices.push(col + row * (subdivisions + 1));
  16367. indices.push(col + (row + 1) * (subdivisions + 1));
  16368. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16369. indices.push(col + row * (subdivisions + 1));
  16370. }
  16371. }
  16372. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16373. var vertexData = new BABYLON.VertexData();
  16374. vertexData.indices = indices;
  16375. vertexData.positions = positions;
  16376. vertexData.normals = normals;
  16377. vertexData.uvs = uvs;
  16378. return vertexData;
  16379. };
  16380. VertexData.CreatePlane = function (size) {
  16381. var indices = [];
  16382. var positions = [];
  16383. var normals = [];
  16384. var uvs = [];
  16385. size = size || 1;
  16386. var halfSize = size / 2.0;
  16387. positions.push(-halfSize, -halfSize, 0);
  16388. normals.push(0, 0, -1.0);
  16389. uvs.push(0.0, 0.0);
  16390. positions.push(halfSize, -halfSize, 0);
  16391. normals.push(0, 0, -1.0);
  16392. uvs.push(1.0, 0.0);
  16393. positions.push(halfSize, halfSize, 0);
  16394. normals.push(0, 0, -1.0);
  16395. uvs.push(1.0, 1.0);
  16396. positions.push(-halfSize, halfSize, 0);
  16397. normals.push(0, 0, -1.0);
  16398. uvs.push(0.0, 1.0);
  16399. indices.push(0);
  16400. indices.push(1);
  16401. indices.push(2);
  16402. indices.push(0);
  16403. indices.push(2);
  16404. indices.push(3);
  16405. var vertexData = new BABYLON.VertexData();
  16406. vertexData.indices = indices;
  16407. vertexData.positions = positions;
  16408. vertexData.normals = normals;
  16409. vertexData.uvs = uvs;
  16410. return vertexData;
  16411. };
  16412. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16413. var indices = [];
  16414. var positions = [];
  16415. var normals = [];
  16416. var uvs = [];
  16417. radius = radius || 2;
  16418. tube = tube || 0.5;
  16419. radialSegments = radialSegments || 32;
  16420. tubularSegments = tubularSegments || 32;
  16421. p = p || 2;
  16422. q = q || 3;
  16423. var getPos = function (angle) {
  16424. var cu = Math.cos(angle);
  16425. var su = Math.sin(angle);
  16426. var quOverP = q / p * angle;
  16427. var cs = Math.cos(quOverP);
  16428. var tx = radius * (2 + cs) * 0.5 * cu;
  16429. var ty = radius * (2 + cs) * su * 0.5;
  16430. var tz = radius * Math.sin(quOverP) * 0.5;
  16431. return new BABYLON.Vector3(tx, ty, tz);
  16432. };
  16433. for (var i = 0; i <= radialSegments; i++) {
  16434. var modI = i % radialSegments;
  16435. var u = modI / radialSegments * 2 * p * Math.PI;
  16436. var p1 = getPos(u);
  16437. var p2 = getPos(u + 0.01);
  16438. var tang = p2.subtract(p1);
  16439. var n = p2.add(p1);
  16440. var bitan = BABYLON.Vector3.Cross(tang, n);
  16441. n = BABYLON.Vector3.Cross(bitan, tang);
  16442. bitan.normalize();
  16443. n.normalize();
  16444. for (var j = 0; j < tubularSegments; j++) {
  16445. var modJ = j % tubularSegments;
  16446. var v = modJ / tubularSegments * 2 * Math.PI;
  16447. var cx = -tube * Math.cos(v);
  16448. var cy = tube * Math.sin(v);
  16449. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16450. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16451. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16452. uvs.push(i / radialSegments);
  16453. uvs.push(j / tubularSegments);
  16454. }
  16455. }
  16456. for (i = 0; i < radialSegments; i++) {
  16457. for (j = 0; j < tubularSegments; j++) {
  16458. var jNext = (j + 1) % tubularSegments;
  16459. var a = i * tubularSegments + j;
  16460. var b = (i + 1) * tubularSegments + j;
  16461. var c = (i + 1) * tubularSegments + jNext;
  16462. var d = i * tubularSegments + jNext;
  16463. indices.push(d);
  16464. indices.push(b);
  16465. indices.push(a);
  16466. indices.push(d);
  16467. indices.push(c);
  16468. indices.push(b);
  16469. }
  16470. }
  16471. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16472. var vertexData = new BABYLON.VertexData();
  16473. vertexData.indices = indices;
  16474. vertexData.positions = positions;
  16475. vertexData.normals = normals;
  16476. vertexData.uvs = uvs;
  16477. return vertexData;
  16478. };
  16479. VertexData.ComputeNormals = function (positions, indices, normals) {
  16480. var positionVectors = [];
  16481. var facesOfVertices = [];
  16482. var index;
  16483. for (index = 0; index < positions.length; index += 3) {
  16484. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16485. positionVectors.push(vector3);
  16486. facesOfVertices.push([]);
  16487. }
  16488. var facesNormals = [];
  16489. for (index = 0; index < indices.length / 3; index++) {
  16490. var i1 = indices[index * 3];
  16491. var i2 = indices[index * 3 + 1];
  16492. var i3 = indices[index * 3 + 2];
  16493. var p1 = positionVectors[i1];
  16494. var p2 = positionVectors[i2];
  16495. var p3 = positionVectors[i3];
  16496. var p1p2 = p1.subtract(p2);
  16497. var p3p2 = p3.subtract(p2);
  16498. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16499. facesOfVertices[i1].push(index);
  16500. facesOfVertices[i2].push(index);
  16501. facesOfVertices[i3].push(index);
  16502. }
  16503. for (index = 0; index < positionVectors.length; index++) {
  16504. var faces = facesOfVertices[index];
  16505. var normal = BABYLON.Vector3.Zero();
  16506. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16507. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16508. }
  16509. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16510. normals[index * 3] = normal.x;
  16511. normals[index * 3 + 1] = normal.y;
  16512. normals[index * 3 + 2] = normal.z;
  16513. }
  16514. };
  16515. return VertexData;
  16516. })();
  16517. BABYLON.VertexData = VertexData;
  16518. })(BABYLON || (BABYLON = {}));
  16519. var __extends = this.__extends || function (d, b) {
  16520. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16521. function __() { this.constructor = d; }
  16522. __.prototype = b.prototype;
  16523. d.prototype = new __();
  16524. };
  16525. var BABYLON;
  16526. (function (BABYLON) {
  16527. var buildCamera = function (that, name) {
  16528. that._leftCamera.isIntermediate = true;
  16529. that.subCameras.push(that._leftCamera);
  16530. that.subCameras.push(that._rightCamera);
  16531. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16532. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16533. that._anaglyphPostProcess.onApply = function (effect) {
  16534. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16535. };
  16536. that._update();
  16537. };
  16538. var AnaglyphArcRotateCamera = (function (_super) {
  16539. __extends(AnaglyphArcRotateCamera, _super);
  16540. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16541. _super.call(this, name, alpha, beta, radius, target, scene);
  16542. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16543. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16544. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16545. buildCamera(this, name);
  16546. }
  16547. AnaglyphArcRotateCamera.prototype._update = function () {
  16548. this._updateCamera(this._leftCamera);
  16549. this._updateCamera(this._rightCamera);
  16550. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16551. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16552. _super.prototype._update.call(this);
  16553. };
  16554. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16555. camera.beta = this.beta;
  16556. camera.radius = this.radius;
  16557. camera.minZ = this.minZ;
  16558. camera.maxZ = this.maxZ;
  16559. camera.fov = this.fov;
  16560. camera.target = this.target;
  16561. };
  16562. return AnaglyphArcRotateCamera;
  16563. })(BABYLON.ArcRotateCamera);
  16564. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16565. var AnaglyphFreeCamera = (function (_super) {
  16566. __extends(AnaglyphFreeCamera, _super);
  16567. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16568. _super.call(this, name, position, scene);
  16569. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16570. this._transformMatrix = new BABYLON.Matrix();
  16571. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16572. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16573. buildCamera(this, name);
  16574. }
  16575. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16576. var target = this.getTarget();
  16577. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16578. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16579. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16580. };
  16581. AnaglyphFreeCamera.prototype._update = function () {
  16582. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16583. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16584. this._updateCamera(this._leftCamera);
  16585. this._updateCamera(this._rightCamera);
  16586. _super.prototype._update.call(this);
  16587. };
  16588. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16589. camera.minZ = this.minZ;
  16590. camera.maxZ = this.maxZ;
  16591. camera.fov = this.fov;
  16592. camera.viewport = this.viewport;
  16593. camera.setTarget(this.getTarget());
  16594. };
  16595. return AnaglyphFreeCamera;
  16596. })(BABYLON.FreeCamera);
  16597. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16598. })(BABYLON || (BABYLON = {}));
  16599. var __extends = this.__extends || function (d, b) {
  16600. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16601. function __() { this.constructor = d; }
  16602. __.prototype = b.prototype;
  16603. d.prototype = new __();
  16604. };
  16605. var BABYLON;
  16606. (function (BABYLON) {
  16607. var AnaglyphPostProcess = (function (_super) {
  16608. __extends(AnaglyphPostProcess, _super);
  16609. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16610. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16611. }
  16612. return AnaglyphPostProcess;
  16613. })(BABYLON.PostProcess);
  16614. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16615. })(BABYLON || (BABYLON = {}));
  16616. var BABYLON;
  16617. (function (BABYLON) {
  16618. var Tags = (function () {
  16619. function Tags() {
  16620. }
  16621. Tags.EnableFor = function (obj) {
  16622. obj._tags = obj._tags || {};
  16623. obj.hasTags = function () {
  16624. return Tags.HasTags(obj);
  16625. };
  16626. obj.addTags = function (tagsString) {
  16627. return Tags.AddTagsTo(obj, tagsString);
  16628. };
  16629. obj.removeTags = function (tagsString) {
  16630. return Tags.RemoveTagsFrom(obj, tagsString);
  16631. };
  16632. obj.matchesTagsQuery = function (tagsQuery) {
  16633. return Tags.MatchesQuery(obj, tagsQuery);
  16634. };
  16635. };
  16636. Tags.DisableFor = function (obj) {
  16637. delete obj._tags;
  16638. delete obj.hasTags;
  16639. delete obj.addTags;
  16640. delete obj.removeTags;
  16641. delete obj.matchesTagsQuery;
  16642. };
  16643. Tags.HasTags = function (obj) {
  16644. if (!obj._tags) {
  16645. return false;
  16646. }
  16647. return !BABYLON.Tools.IsEmpty(obj._tags);
  16648. };
  16649. Tags.GetTags = function (obj) {
  16650. if (!obj._tags) {
  16651. return null;
  16652. }
  16653. return obj._tags;
  16654. };
  16655. Tags.AddTagsTo = function (obj, tagsString) {
  16656. if (!tagsString) {
  16657. return;
  16658. }
  16659. var tags = tagsString.split(" ");
  16660. for (var t in tags) {
  16661. Tags._AddTagTo(obj, tags[t]);
  16662. }
  16663. };
  16664. Tags._AddTagTo = function (obj, tag) {
  16665. tag = tag.trim();
  16666. if (tag === "" || tag === "true" || tag === "false") {
  16667. return;
  16668. }
  16669. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16670. return;
  16671. }
  16672. Tags.EnableFor(obj);
  16673. obj._tags[tag] = true;
  16674. };
  16675. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16676. if (!Tags.HasTags(obj)) {
  16677. return;
  16678. }
  16679. var tags = tagsString.split(" ");
  16680. for (var t in tags) {
  16681. Tags._RemoveTagFrom(obj, tags[t]);
  16682. }
  16683. };
  16684. Tags._RemoveTagFrom = function (obj, tag) {
  16685. delete obj._tags[tag];
  16686. };
  16687. Tags.MatchesQuery = function (obj, tagsQuery) {
  16688. if (tagsQuery === undefined) {
  16689. return true;
  16690. }
  16691. if (tagsQuery === "") {
  16692. return Tags.HasTags(obj);
  16693. }
  16694. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16695. return Tags.HasTags(obj) && obj._tags[r];
  16696. });
  16697. };
  16698. return Tags;
  16699. })();
  16700. BABYLON.Tags = Tags;
  16701. })(BABYLON || (BABYLON = {}));
  16702. var BABYLON;
  16703. (function (BABYLON) {
  16704. (function (Internals) {
  16705. var AndOrNotEvaluator = (function () {
  16706. function AndOrNotEvaluator() {
  16707. }
  16708. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16709. if (!query.match(/\([^\(\)]*\)/g)) {
  16710. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16711. } else {
  16712. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16713. r = r.slice(1, r.length - 1);
  16714. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16715. });
  16716. }
  16717. if (query === "true") {
  16718. return true;
  16719. }
  16720. if (query === "false") {
  16721. return false;
  16722. }
  16723. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16724. };
  16725. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16726. evaluateCallback = evaluateCallback || (function (r) {
  16727. return r === "true" ? true : false;
  16728. });
  16729. var result;
  16730. var or = parenthesisContent.split("||");
  16731. for (var i in or) {
  16732. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16733. var and = ori.split("&&");
  16734. if (and.length > 1) {
  16735. for (var j = 0; j < and.length; ++j) {
  16736. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16737. if (andj !== "true" && andj !== "false") {
  16738. if (andj[0] === "!") {
  16739. result = !evaluateCallback(andj.substring(1));
  16740. } else {
  16741. result = evaluateCallback(andj);
  16742. }
  16743. } else {
  16744. result = andj === "true" ? true : false;
  16745. }
  16746. if (!result) {
  16747. ori = "false";
  16748. break;
  16749. }
  16750. }
  16751. }
  16752. if (result || ori === "true") {
  16753. result = true;
  16754. break;
  16755. }
  16756. if (ori !== "true" && ori !== "false") {
  16757. if (ori[0] === "!") {
  16758. result = !evaluateCallback(ori.substring(1));
  16759. } else {
  16760. result = evaluateCallback(ori);
  16761. }
  16762. } else {
  16763. result = ori === "true" ? true : false;
  16764. }
  16765. }
  16766. return result ? "true" : "false";
  16767. };
  16768. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16769. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16770. r = r.replace(/[\s]/g, function () {
  16771. return "";
  16772. });
  16773. return r.length % 2 ? "!" : "";
  16774. });
  16775. booleanString = booleanString.trim();
  16776. if (booleanString === "!true") {
  16777. booleanString = "false";
  16778. } else if (booleanString === "!false") {
  16779. booleanString = "true";
  16780. }
  16781. return booleanString;
  16782. };
  16783. return AndOrNotEvaluator;
  16784. })();
  16785. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16786. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16787. var Internals = BABYLON.Internals;
  16788. })(BABYLON || (BABYLON = {}));
  16789. var BABYLON;
  16790. (function (BABYLON) {
  16791. var PostProcessRenderPass = (function () {
  16792. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16793. this._enabled = true;
  16794. this._refCount = 0;
  16795. this._name = name;
  16796. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16797. this.setRenderList(renderList);
  16798. this._renderTexture.onBeforeRender = beforeRender;
  16799. this._renderTexture.onAfterRender = afterRender;
  16800. this._scene = scene;
  16801. }
  16802. PostProcessRenderPass.prototype._incRefCount = function () {
  16803. if (this._refCount === 0) {
  16804. this._scene.customRenderTargets.push(this._renderTexture);
  16805. }
  16806. return ++this._refCount;
  16807. };
  16808. PostProcessRenderPass.prototype._decRefCount = function () {
  16809. this._refCount--;
  16810. if (this._refCount <= 0) {
  16811. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16812. }
  16813. return this._refCount;
  16814. };
  16815. PostProcessRenderPass.prototype._update = function () {
  16816. this.setRenderList(this._renderList);
  16817. };
  16818. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16819. this._renderTexture.renderList = renderList;
  16820. };
  16821. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16822. return this._renderTexture;
  16823. };
  16824. return PostProcessRenderPass;
  16825. })();
  16826. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16827. })(BABYLON || (BABYLON = {}));
  16828. var BABYLON;
  16829. (function (BABYLON) {
  16830. var PostProcessRenderEffect = (function () {
  16831. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16832. this._engine = engine;
  16833. this._name = name;
  16834. this._postProcessType = postProcessType;
  16835. this._ratio = ratio || 1.0;
  16836. this._samplingMode = samplingMode || null;
  16837. this._singleInstance = singleInstance || true;
  16838. this._cameras = [];
  16839. this._postProcesses = [];
  16840. this._indicesForCamera = [];
  16841. this._renderPasses = [];
  16842. this._renderEffectAsPasses = [];
  16843. this.parameters = function (effect) {
  16844. };
  16845. }
  16846. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16847. var postProcess;
  16848. var instance;
  16849. var args = [];
  16850. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16851. for (var i = 0; i < parameters.length; i++) {
  16852. switch (parameters[i]) {
  16853. case "name":
  16854. args[i] = postProcessType.toString();
  16855. break;
  16856. case "ratio":
  16857. args[i] = ratio;
  16858. break;
  16859. case "camera":
  16860. args[i] = null;
  16861. break;
  16862. case "samplingMode":
  16863. args[i] = samplingMode;
  16864. break;
  16865. case "engine":
  16866. args[i] = engine;
  16867. break;
  16868. case "reusable":
  16869. args[i] = true;
  16870. break;
  16871. default:
  16872. args[i] = null;
  16873. break;
  16874. }
  16875. }
  16876. postProcess = function () {
  16877. };
  16878. postProcess.prototype = postProcessType.prototype;
  16879. instance = new postProcess();
  16880. postProcessType.apply(instance, args);
  16881. return instance;
  16882. };
  16883. PostProcessRenderEffect._GetParametersNames = function (func) {
  16884. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16885. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16886. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16887. if (parameters === null)
  16888. parameters = [];
  16889. return parameters;
  16890. };
  16891. PostProcessRenderEffect.prototype._update = function () {
  16892. for (var renderPassName in this._renderPasses) {
  16893. this._renderPasses[renderPassName]._update();
  16894. }
  16895. };
  16896. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16897. this._renderPasses[renderPass._name] = renderPass;
  16898. this._linkParameters();
  16899. };
  16900. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  16901. delete this._renderPasses[renderPass._name];
  16902. this._linkParameters();
  16903. };
  16904. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  16905. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  16906. this._linkParameters();
  16907. };
  16908. PostProcessRenderEffect.prototype.getPass = function (passName) {
  16909. for (var renderPassName in this._renderPasses) {
  16910. if (renderPassName === passName) {
  16911. return this._renderPasses[passName];
  16912. }
  16913. }
  16914. };
  16915. PostProcessRenderEffect.prototype.emptyPasses = function () {
  16916. this._renderPasses.length = 0;
  16917. this._linkParameters();
  16918. };
  16919. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  16920. var cameraKey;
  16921. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16922. for (var i = 0; i < _cam.length; i++) {
  16923. var camera = _cam[i];
  16924. var cameraName = camera.name;
  16925. if (this._singleInstance) {
  16926. cameraKey = 0;
  16927. } else {
  16928. cameraKey = cameraName;
  16929. }
  16930. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  16931. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  16932. if (this._indicesForCamera[cameraName] === null) {
  16933. this._indicesForCamera[cameraName] = [];
  16934. }
  16935. this._indicesForCamera[cameraName].push(index);
  16936. if (this._cameras.indexOf(camera) === -1) {
  16937. this._cameras[cameraName] = camera;
  16938. }
  16939. for (var passName in this._renderPasses) {
  16940. this._renderPasses[passName]._incRefCount();
  16941. }
  16942. }
  16943. this._linkParameters();
  16944. };
  16945. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  16946. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16947. for (var i = 0; i < _cam.length; i++) {
  16948. var camera = _cam[i];
  16949. var cameraName = camera.name;
  16950. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16951. var index = this._cameras.indexOf(cameraName);
  16952. this._indicesForCamera.splice(index, 1);
  16953. this._cameras.splice(index, 1);
  16954. for (var passName in this._renderPasses) {
  16955. this._renderPasses[passName]._decRefCount();
  16956. }
  16957. }
  16958. };
  16959. PostProcessRenderEffect.prototype._enable = function (cameras) {
  16960. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16961. for (var i = 0; i < _cam.length; i++) {
  16962. var camera = _cam[i];
  16963. var cameraName = camera.name;
  16964. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  16965. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  16966. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  16967. }
  16968. }
  16969. for (var passName in this._renderPasses) {
  16970. this._renderPasses[passName]._incRefCount();
  16971. }
  16972. }
  16973. };
  16974. PostProcessRenderEffect.prototype._disable = function (cameras) {
  16975. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16976. for (var i = 0; i < _cam.length; i++) {
  16977. var camera = _cam[i];
  16978. var cameraName = camera.Name;
  16979. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16980. for (var passName in this._renderPasses) {
  16981. this._renderPasses[passName]._decRefCount();
  16982. }
  16983. }
  16984. };
  16985. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  16986. if (this._singleInstance) {
  16987. return this._postProcesses[0];
  16988. } else {
  16989. return this._postProcesses[camera.name];
  16990. }
  16991. };
  16992. PostProcessRenderEffect.prototype._linkParameters = function () {
  16993. var _this = this;
  16994. for (var index in this._postProcesses) {
  16995. this._postProcesses[index].onApply = function (effect) {
  16996. _this.parameters(effect);
  16997. _this._linkTextures(effect);
  16998. };
  16999. }
  17000. };
  17001. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17002. for (var renderPassName in this._renderPasses) {
  17003. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17004. }
  17005. for (var renderEffectName in this._renderEffectAsPasses) {
  17006. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17007. }
  17008. };
  17009. return PostProcessRenderEffect;
  17010. })();
  17011. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17012. })(BABYLON || (BABYLON = {}));
  17013. var BABYLON;
  17014. (function (BABYLON) {
  17015. var PostProcessRenderPipeline = (function () {
  17016. function PostProcessRenderPipeline(engine, name) {
  17017. this._engine = engine;
  17018. this._name = name;
  17019. this._renderEffects = [];
  17020. this._renderEffectsForIsolatedPass = [];
  17021. this._cameras = [];
  17022. }
  17023. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17024. this._renderEffects[renderEffect._name] = renderEffect;
  17025. };
  17026. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17027. var renderEffects = this._renderEffects[renderEffectName];
  17028. if (!renderEffects) {
  17029. return;
  17030. }
  17031. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17032. };
  17033. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17034. var renderEffects = this._renderEffects[renderEffectName];
  17035. if (!renderEffects) {
  17036. return;
  17037. }
  17038. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17039. };
  17040. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17041. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17042. var indicesToDelete = [];
  17043. for (var i = 0; i < _cam.length; i++) {
  17044. var camera = _cam[i];
  17045. var cameraName = camera.name;
  17046. if (this._cameras.indexOf(camera) === -1) {
  17047. this._cameras[cameraName] = camera;
  17048. } else if (unique) {
  17049. indicesToDelete.push(i);
  17050. }
  17051. }
  17052. for (var i = 0; i < indicesToDelete.length; i++) {
  17053. cameras.splice(indicesToDelete[i], 1);
  17054. }
  17055. for (var renderEffectName in this._renderEffects) {
  17056. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17057. }
  17058. };
  17059. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17060. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17061. for (var renderEffectName in this._renderEffects) {
  17062. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17063. }
  17064. for (var i = 0; i < _cam.length; i++) {
  17065. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17066. }
  17067. };
  17068. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17069. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17070. var pass = null;
  17071. for (var renderEffectName in this._renderEffects) {
  17072. pass = this._renderEffects[renderEffectName].getPass(passName);
  17073. if (pass != null) {
  17074. break;
  17075. }
  17076. }
  17077. if (pass === null) {
  17078. return;
  17079. }
  17080. for (var renderEffectName in this._renderEffects) {
  17081. this._renderEffects[renderEffectName]._disable(_cam);
  17082. }
  17083. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17084. for (var i = 0; i < _cam.length; i++) {
  17085. var camera = _cam[i];
  17086. var cameraName = camera.name;
  17087. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17088. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17089. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17090. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17091. }
  17092. };
  17093. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17094. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17095. for (var i = 0; i < _cam.length; i++) {
  17096. var camera = _cam[i];
  17097. var cameraName = camera.name;
  17098. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17099. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17100. }
  17101. for (var renderEffectName in this._renderEffects) {
  17102. this._renderEffects[renderEffectName]._enable(_cam);
  17103. }
  17104. };
  17105. PostProcessRenderPipeline.prototype._update = function () {
  17106. for (var renderEffectName in this._renderEffects) {
  17107. this._renderEffects[renderEffectName]._update();
  17108. }
  17109. for (var i = 0; i < this._cameras.length; i++) {
  17110. var cameraName = this._cameras[i].name;
  17111. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17112. this._renderEffectsForIsolatedPass[cameraName]._update();
  17113. }
  17114. }
  17115. };
  17116. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17117. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17118. return PostProcessRenderPipeline;
  17119. })();
  17120. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17121. })(BABYLON || (BABYLON = {}));
  17122. var BABYLON;
  17123. (function (BABYLON) {
  17124. var PostProcessRenderPipelineManager = (function () {
  17125. function PostProcessRenderPipelineManager() {
  17126. this._renderPipelines = [];
  17127. }
  17128. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17129. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17130. };
  17131. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17132. var renderPipeline = this._renderPipelines[renderPipelineName];
  17133. if (!renderPipeline) {
  17134. return;
  17135. }
  17136. renderPipeline.attachCameras(cameras, unique);
  17137. };
  17138. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17139. var renderPipeline = this._renderPipelines[renderPipelineName];
  17140. if (!renderPipeline) {
  17141. return;
  17142. }
  17143. renderPipeline.detachCameras(cameras);
  17144. };
  17145. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17146. var renderPipeline = this._renderPipelines[renderPipelineName];
  17147. if (!renderPipeline) {
  17148. return;
  17149. }
  17150. renderPipeline.enableEffect(renderEffectName, cameras);
  17151. };
  17152. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17153. var renderPipeline = this._renderPipelines[renderPipelineName];
  17154. if (!renderPipeline) {
  17155. return;
  17156. }
  17157. renderPipeline.disableEffect(renderEffectName, cameras);
  17158. };
  17159. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17160. var renderPipeline = this._renderPipelines[renderPipelineName];
  17161. if (!renderPipeline) {
  17162. return;
  17163. }
  17164. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17165. };
  17166. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17167. var renderPipeline = this._renderPipelines[renderPipelineName];
  17168. if (!renderPipeline) {
  17169. return;
  17170. }
  17171. renderPipeline.disableDisplayOnlyPass(cameras);
  17172. };
  17173. PostProcessRenderPipelineManager.prototype.update = function () {
  17174. for (var renderPipelineName in this._renderPipelines) {
  17175. this._renderPipelines[renderPipelineName]._update();
  17176. }
  17177. };
  17178. return PostProcessRenderPipelineManager;
  17179. })();
  17180. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17181. })(BABYLON || (BABYLON = {}));
  17182. var __extends = this.__extends || function (d, b) {
  17183. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17184. function __() { this.constructor = d; }
  17185. __.prototype = b.prototype;
  17186. d.prototype = new __();
  17187. };
  17188. var BABYLON;
  17189. (function (BABYLON) {
  17190. var DisplayPassPostProcess = (function (_super) {
  17191. __extends(DisplayPassPostProcess, _super);
  17192. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17193. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17194. }
  17195. return DisplayPassPostProcess;
  17196. })(BABYLON.PostProcess);
  17197. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17198. })(BABYLON || (BABYLON = {}));
  17199. var BABYLON;
  17200. (function (BABYLON) {
  17201. var BoundingBoxRenderer = (function () {
  17202. function BoundingBoxRenderer(scene) {
  17203. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17204. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17205. this.showBackLines = true;
  17206. this.renderList = new BABYLON.SmartArray(32);
  17207. this._scene = scene;
  17208. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17209. attributes: ["position"],
  17210. uniforms: ["worldViewProjection", "color"]
  17211. });
  17212. var engine = this._scene.getEngine();
  17213. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17214. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17215. 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]);
  17216. }
  17217. BoundingBoxRenderer.prototype.reset = function () {
  17218. this.renderList.reset();
  17219. };
  17220. BoundingBoxRenderer.prototype.render = function () {
  17221. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17222. return;
  17223. }
  17224. var engine = this._scene.getEngine();
  17225. engine.setDepthWrite(false);
  17226. this._colorShader._preBind();
  17227. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17228. var boundingBox = this.renderList.data[boundingBoxIndex];
  17229. var min = boundingBox.minimum;
  17230. var max = boundingBox.maximum;
  17231. var diff = max.subtract(min);
  17232. var median = min.add(diff.scale(0.5));
  17233. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17234. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17235. if (this.showBackLines) {
  17236. engine.setDepthFunctionToGreaterOrEqual();
  17237. this._colorShader.setColor4("color", this.backColor.toColor4());
  17238. this._colorShader.bind(worldMatrix);
  17239. engine.draw(false, 0, 24);
  17240. }
  17241. engine.setDepthFunctionToLess();
  17242. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17243. this._colorShader.bind(worldMatrix);
  17244. engine.draw(false, 0, 24);
  17245. }
  17246. this._colorShader.unbind();
  17247. engine.setDepthFunctionToLessOrEqual();
  17248. engine.setDepthWrite(true);
  17249. };
  17250. BoundingBoxRenderer.prototype.dispose = function () {
  17251. this._colorShader.dispose();
  17252. this._vb.dispose();
  17253. this._scene.getEngine()._releaseBuffer(this._ib);
  17254. };
  17255. return BoundingBoxRenderer;
  17256. })();
  17257. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17258. })(BABYLON || (BABYLON = {}));
  17259. /**
  17260. * Based on jsTGALoader - Javascript loader for TGA file
  17261. * By Vincent Thibault
  17262. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17263. */
  17264. var BABYLON;
  17265. (function (BABYLON) {
  17266. (function (Internals) {
  17267. var TGATools = (function () {
  17268. function TGATools() {
  17269. }
  17270. TGATools.GetTGAHeader = function (data) {
  17271. var offset = 0;
  17272. var header = {
  17273. id_length: data[offset++],
  17274. colormap_type: data[offset++],
  17275. image_type: data[offset++],
  17276. colormap_index: data[offset++] | data[offset++] << 8,
  17277. colormap_length: data[offset++] | data[offset++] << 8,
  17278. colormap_size: data[offset++],
  17279. origin: [
  17280. data[offset++] | data[offset++] << 8,
  17281. data[offset++] | data[offset++] << 8
  17282. ],
  17283. width: data[offset++] | data[offset++] << 8,
  17284. height: data[offset++] | data[offset++] << 8,
  17285. pixel_size: data[offset++],
  17286. flags: data[offset++]
  17287. };
  17288. return header;
  17289. };
  17290. TGATools.UploadContent = function (gl, data) {
  17291. if (data.length < 19) {
  17292. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17293. return;
  17294. }
  17295. var offset = 18;
  17296. var header = TGATools.GetTGAHeader(data);
  17297. if (header.id_length + offset > data.length) {
  17298. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17299. return;
  17300. }
  17301. offset += header.id_length;
  17302. var use_rle = false;
  17303. var use_pal = false;
  17304. var use_rgb = false;
  17305. var use_grey = false;
  17306. switch (header.image_type) {
  17307. case TGATools._TYPE_RLE_INDEXED:
  17308. use_rle = true;
  17309. case TGATools._TYPE_INDEXED:
  17310. use_pal = true;
  17311. break;
  17312. case TGATools._TYPE_RLE_RGB:
  17313. use_rle = true;
  17314. case TGATools._TYPE_RGB:
  17315. use_rgb = true;
  17316. break;
  17317. case TGATools._TYPE_RLE_GREY:
  17318. use_rle = true;
  17319. case TGATools._TYPE_GREY:
  17320. use_grey = true;
  17321. break;
  17322. }
  17323. var pixel_data;
  17324. var numAlphaBits = header.flags & 0xf;
  17325. var pixel_size = header.pixel_size >> 3;
  17326. var pixel_total = header.width * header.height * pixel_size;
  17327. var palettes;
  17328. if (use_pal) {
  17329. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17330. }
  17331. if (use_rle) {
  17332. pixel_data = new Uint8Array(pixel_total);
  17333. var c, count, i;
  17334. var localOffset = 0;
  17335. var pixels = new Uint8Array(pixel_size);
  17336. while (offset < pixel_total && localOffset < pixel_total) {
  17337. c = data[offset++];
  17338. count = (c & 0x7f) + 1;
  17339. if (c & 0x80) {
  17340. for (i = 0; i < pixel_size; ++i) {
  17341. pixels[i] = data[offset++];
  17342. }
  17343. for (i = 0; i < count; ++i) {
  17344. pixel_data.set(pixels, localOffset + i * pixel_size);
  17345. }
  17346. localOffset += pixel_size * count;
  17347. } else {
  17348. count *= pixel_size;
  17349. for (i = 0; i < count; ++i) {
  17350. pixel_data[localOffset + i] = data[offset++];
  17351. }
  17352. localOffset += count;
  17353. }
  17354. }
  17355. } else {
  17356. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17357. }
  17358. var x_start, y_start, x_step, y_step, y_end, x_end;
  17359. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17360. default:
  17361. case TGATools._ORIGIN_UL:
  17362. x_start = 0;
  17363. x_step = 1;
  17364. x_end = header.width;
  17365. y_start = 0;
  17366. y_step = 1;
  17367. y_end = header.height;
  17368. break;
  17369. case TGATools._ORIGIN_BL:
  17370. x_start = 0;
  17371. x_step = 1;
  17372. x_end = header.width;
  17373. y_start = header.height - 1;
  17374. y_step = -1;
  17375. y_end = -1;
  17376. break;
  17377. case TGATools._ORIGIN_UR:
  17378. x_start = header.width - 1;
  17379. x_step = -1;
  17380. x_end = -1;
  17381. y_start = 0;
  17382. y_step = 1;
  17383. y_end = header.height;
  17384. break;
  17385. case TGATools._ORIGIN_BR:
  17386. x_start = header.width - 1;
  17387. x_step = -1;
  17388. x_end = -1;
  17389. y_start = header.height - 1;
  17390. y_step = -1;
  17391. y_end = -1;
  17392. break;
  17393. }
  17394. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17395. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17396. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17397. };
  17398. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17399. var image = pixel_data, colormap = palettes;
  17400. var width = header.width, height = header.height;
  17401. var color, i = 0, x, y;
  17402. var imageData = new Uint8Array(width * height * 4);
  17403. for (y = y_start; y !== y_end; y += y_step) {
  17404. for (x = x_start; x !== x_end; x += x_step, i++) {
  17405. color = image[i];
  17406. imageData[(x + width * y) * 4 + 3] = 255;
  17407. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17408. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17409. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17410. }
  17411. }
  17412. return imageData;
  17413. };
  17414. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17415. var image = pixel_data;
  17416. var width = header.width, height = header.height;
  17417. var color, i = 0, x, y;
  17418. var imageData = new Uint8Array(width * height * 4);
  17419. for (y = y_start; y !== y_end; y += y_step) {
  17420. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17421. color = image[i + 0] + (image[i + 1] << 8);
  17422. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17423. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17424. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17425. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17426. }
  17427. }
  17428. return imageData;
  17429. };
  17430. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17431. var image = pixel_data;
  17432. var width = header.width, height = header.height;
  17433. var i = 0, x, y;
  17434. var imageData = new Uint8Array(width * height * 4);
  17435. for (y = y_start; y !== y_end; y += y_step) {
  17436. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17437. imageData[(x + width * y) * 4 + 3] = 255;
  17438. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17439. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17440. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17441. }
  17442. }
  17443. return imageData;
  17444. };
  17445. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17446. var image = pixel_data;
  17447. var width = header.width, height = header.height;
  17448. var i = 0, x, y;
  17449. var imageData = new Uint8Array(width * height * 4);
  17450. for (y = y_start; y !== y_end; y += y_step) {
  17451. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17452. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17453. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17454. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17455. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17456. }
  17457. }
  17458. return imageData;
  17459. };
  17460. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17461. var image = pixel_data;
  17462. var width = header.width, height = header.height;
  17463. var color, i = 0, x, y;
  17464. var imageData = new Uint8Array(width * height * 4);
  17465. for (y = y_start; y !== y_end; y += y_step) {
  17466. for (x = x_start; x !== x_end; x += x_step, i++) {
  17467. color = image[i];
  17468. imageData[(x + width * y) * 4 + 0] = color;
  17469. imageData[(x + width * y) * 4 + 1] = color;
  17470. imageData[(x + width * y) * 4 + 2] = color;
  17471. imageData[(x + width * y) * 4 + 3] = 255;
  17472. }
  17473. }
  17474. return imageData;
  17475. };
  17476. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17477. var image = pixel_data;
  17478. var width = header.width, height = header.height;
  17479. var i = 0, x, y;
  17480. var imageData = new Uint8Array(width * height * 4);
  17481. for (y = y_start; y !== y_end; y += y_step) {
  17482. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17483. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17484. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17485. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17486. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17487. }
  17488. }
  17489. return imageData;
  17490. };
  17491. TGATools._TYPE_NO_DATA = 0;
  17492. TGATools._TYPE_INDEXED = 1;
  17493. TGATools._TYPE_RGB = 2;
  17494. TGATools._TYPE_GREY = 3;
  17495. TGATools._TYPE_RLE_INDEXED = 9;
  17496. TGATools._TYPE_RLE_RGB = 10;
  17497. TGATools._TYPE_RLE_GREY = 11;
  17498. TGATools._ORIGIN_MASK = 0x30;
  17499. TGATools._ORIGIN_SHIFT = 0x04;
  17500. TGATools._ORIGIN_BL = 0x00;
  17501. TGATools._ORIGIN_BR = 0x01;
  17502. TGATools._ORIGIN_UL = 0x02;
  17503. TGATools._ORIGIN_UR = 0x03;
  17504. return TGATools;
  17505. })();
  17506. Internals.TGATools = TGATools;
  17507. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17508. var Internals = BABYLON.Internals;
  17509. })(BABYLON || (BABYLON = {}));
  17510. var BABYLON;
  17511. (function (BABYLON) {
  17512. (function (Internals) {
  17513. var DDS_MAGIC = 0x20534444;
  17514. 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;
  17515. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17516. 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;
  17517. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17518. function FourCCToInt32(value) {
  17519. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17520. }
  17521. function Int32ToFourCC(value) {
  17522. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17523. }
  17524. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17525. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17526. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17527. var headerLengthInt = 31;
  17528. var off_magic = 0;
  17529. var off_size = 1;
  17530. var off_flags = 2;
  17531. var off_height = 3;
  17532. var off_width = 4;
  17533. var off_mipmapCount = 7;
  17534. var off_pfFlags = 20;
  17535. var off_pfFourCC = 21;
  17536. var off_RGBbpp = 22;
  17537. var off_RMask = 23;
  17538. var off_GMask = 24;
  17539. var off_BMask = 25;
  17540. var off_AMask = 26;
  17541. var off_caps1 = 27;
  17542. var off_caps2 = 28;
  17543. ;
  17544. var DDSTools = (function () {
  17545. function DDSTools() {
  17546. }
  17547. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17548. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17549. var mipmapCount = 1;
  17550. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17551. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17552. }
  17553. return {
  17554. width: header[off_width],
  17555. height: header[off_height],
  17556. mipmapCount: mipmapCount,
  17557. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17558. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17559. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17560. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17561. };
  17562. };
  17563. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17564. var byteArray = new Uint8Array(dataLength);
  17565. var srcData = new Uint8Array(arrayBuffer);
  17566. var index = 0;
  17567. for (var y = height - 1; y >= 0; y--) {
  17568. for (var x = 0; x < width; x++) {
  17569. var srcPos = dataOffset + (x + y * width) * 4;
  17570. byteArray[index + 2] = srcData[srcPos];
  17571. byteArray[index + 1] = srcData[srcPos + 1];
  17572. byteArray[index] = srcData[srcPos + 2];
  17573. byteArray[index + 3] = srcData[srcPos + 3];
  17574. index += 4;
  17575. }
  17576. }
  17577. return byteArray;
  17578. };
  17579. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17580. var byteArray = new Uint8Array(dataLength);
  17581. var srcData = new Uint8Array(arrayBuffer);
  17582. var index = 0;
  17583. for (var y = height - 1; y >= 0; y--) {
  17584. for (var x = 0; x < width; x++) {
  17585. var srcPos = dataOffset + (x + y * width) * 3;
  17586. byteArray[index + 2] = srcData[srcPos];
  17587. byteArray[index + 1] = srcData[srcPos + 1];
  17588. byteArray[index] = srcData[srcPos + 2];
  17589. index += 3;
  17590. }
  17591. }
  17592. return byteArray;
  17593. };
  17594. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17595. var byteArray = new Uint8Array(dataLength);
  17596. var srcData = new Uint8Array(arrayBuffer);
  17597. var index = 0;
  17598. for (var y = height - 1; y >= 0; y--) {
  17599. for (var x = 0; x < width; x++) {
  17600. var srcPos = dataOffset + (x + y * width);
  17601. byteArray[index] = srcData[srcPos];
  17602. index++;
  17603. }
  17604. }
  17605. return byteArray;
  17606. };
  17607. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17608. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17609. if (header[off_magic] != DDS_MAGIC) {
  17610. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17611. return;
  17612. }
  17613. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17614. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17615. return;
  17616. }
  17617. if (info.isFourCC) {
  17618. fourCC = header[off_pfFourCC];
  17619. switch (fourCC) {
  17620. case FOURCC_DXT1:
  17621. blockBytes = 8;
  17622. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17623. break;
  17624. case FOURCC_DXT3:
  17625. blockBytes = 16;
  17626. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17627. break;
  17628. case FOURCC_DXT5:
  17629. blockBytes = 16;
  17630. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17631. break;
  17632. default:
  17633. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17634. return;
  17635. }
  17636. }
  17637. mipmapCount = 1;
  17638. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17639. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17640. }
  17641. var bpp = header[off_RGBbpp];
  17642. for (var face = 0; face < faces; face++) {
  17643. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17644. width = header[off_width];
  17645. height = header[off_height];
  17646. dataOffset = header[off_size] + 4;
  17647. for (i = 0; i < mipmapCount; ++i) {
  17648. if (info.isRGB) {
  17649. if (bpp == 24) {
  17650. dataLength = width * height * 3;
  17651. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17652. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17653. } else {
  17654. dataLength = width * height * 4;
  17655. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17656. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17657. }
  17658. } else if (info.isLuminance) {
  17659. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17660. var unpaddedRowSize = width;
  17661. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17662. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17663. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17664. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17665. } else {
  17666. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17667. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17668. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17669. }
  17670. dataOffset += dataLength;
  17671. width *= 0.5;
  17672. height *= 0.5;
  17673. width = Math.max(1.0, width);
  17674. height = Math.max(1.0, height);
  17675. }
  17676. }
  17677. };
  17678. return DDSTools;
  17679. })();
  17680. Internals.DDSTools = DDSTools;
  17681. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17682. var Internals = BABYLON.Internals;
  17683. })(BABYLON || (BABYLON = {}));
  17684. var BABYLON;
  17685. (function (BABYLON) {
  17686. var SmartArray = (function () {
  17687. function SmartArray(capacity) {
  17688. this.length = 0;
  17689. this._duplicateId = 0;
  17690. this.data = new Array(capacity);
  17691. this._id = SmartArray._GlobalId++;
  17692. }
  17693. SmartArray.prototype.push = function (value) {
  17694. this.data[this.length++] = value;
  17695. if (this.length > this.data.length) {
  17696. this.data.length *= 2;
  17697. }
  17698. if (!value.__smartArrayFlags) {
  17699. value.__smartArrayFlags = {};
  17700. }
  17701. value.__smartArrayFlags[this._id] = this._duplicateId;
  17702. };
  17703. SmartArray.prototype.pushNoDuplicate = function (value) {
  17704. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17705. return;
  17706. }
  17707. this.push(value);
  17708. };
  17709. SmartArray.prototype.sort = function (compareFn) {
  17710. this.data.sort(compareFn);
  17711. };
  17712. SmartArray.prototype.reset = function () {
  17713. this.length = 0;
  17714. this._duplicateId++;
  17715. };
  17716. SmartArray.prototype.concat = function (array) {
  17717. if (array.length === 0) {
  17718. return;
  17719. }
  17720. if (this.length + array.length > this.data.length) {
  17721. this.data.length = (this.length + array.length) * 2;
  17722. }
  17723. for (var index = 0; index < array.length; index++) {
  17724. this.data[this.length++] = (array.data || array)[index];
  17725. }
  17726. };
  17727. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17728. if (array.length === 0) {
  17729. return;
  17730. }
  17731. if (this.length + array.length > this.data.length) {
  17732. this.data.length = (this.length + array.length) * 2;
  17733. }
  17734. for (var index = 0; index < array.length; index++) {
  17735. var item = (array.data || array)[index];
  17736. this.pushNoDuplicate(item);
  17737. }
  17738. };
  17739. SmartArray.prototype.indexOf = function (value) {
  17740. var position = this.data.indexOf(value);
  17741. if (position >= this.length) {
  17742. return -1;
  17743. }
  17744. return position;
  17745. };
  17746. SmartArray._GlobalId = 0;
  17747. return SmartArray;
  17748. })();
  17749. BABYLON.SmartArray = SmartArray;
  17750. })(BABYLON || (BABYLON = {}));
  17751. var BABYLON;
  17752. (function (BABYLON) {
  17753. var CannonJSPlugin = (function () {
  17754. function CannonJSPlugin() {
  17755. this._registeredMeshes = [];
  17756. this._physicsMaterials = [];
  17757. this.updateBodyPosition = function (mesh) {
  17758. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17759. var registeredMesh = this._registeredMeshes[index];
  17760. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17761. var body = registeredMesh.body.body;
  17762. var center = mesh.getBoundingInfo().boundingBox.center;
  17763. body.position.set(center.x, center.z, center.y);
  17764. body.quaternion.x = mesh.rotationQuaternion.x;
  17765. body.quaternion.z = mesh.rotationQuaternion.y;
  17766. body.quaternion.y = mesh.rotationQuaternion.z;
  17767. body.quaternion.w = -mesh.rotationQuaternion.w;
  17768. return;
  17769. }
  17770. }
  17771. };
  17772. }
  17773. CannonJSPlugin.prototype.initialize = function (iterations) {
  17774. if (typeof iterations === "undefined") { iterations = 10; }
  17775. this._world = new CANNON.World();
  17776. this._world.broadphase = new CANNON.NaiveBroadphase();
  17777. this._world.solver.iterations = iterations;
  17778. };
  17779. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17780. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17781. };
  17782. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17783. this._world.step(delta);
  17784. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17785. var registeredMesh = this._registeredMeshes[index];
  17786. if (registeredMesh.isChild) {
  17787. continue;
  17788. }
  17789. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17790. var deltaPos = registeredMesh.delta;
  17791. if (deltaPos) {
  17792. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17793. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17794. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17795. } else {
  17796. registeredMesh.mesh.position.x = bodyX;
  17797. registeredMesh.mesh.position.y = bodyZ;
  17798. registeredMesh.mesh.position.z = bodyY;
  17799. }
  17800. if (!registeredMesh.mesh.rotationQuaternion) {
  17801. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17802. }
  17803. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17804. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17805. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17806. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17807. }
  17808. };
  17809. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17810. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17811. };
  17812. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17813. this.unregisterMesh(mesh);
  17814. mesh.computeWorldMatrix(true);
  17815. switch (impostor) {
  17816. case BABYLON.PhysicsEngine.SphereImpostor:
  17817. var bbox = mesh.getBoundingInfo().boundingBox;
  17818. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17819. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17820. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17821. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17822. case BABYLON.PhysicsEngine.BoxImpostor:
  17823. bbox = mesh.getBoundingInfo().boundingBox;
  17824. var min = bbox.minimumWorld;
  17825. var max = bbox.maximumWorld;
  17826. var box = max.subtract(min).scale(0.5);
  17827. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17828. case BABYLON.PhysicsEngine.PlaneImpostor:
  17829. return this._createPlane(mesh, options);
  17830. case BABYLON.PhysicsEngine.MeshImpostor:
  17831. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17832. var rawFaces = mesh.getIndices();
  17833. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17834. }
  17835. return null;
  17836. };
  17837. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17838. var shape = new CANNON.Sphere(radius);
  17839. if (!options) {
  17840. return shape;
  17841. }
  17842. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17843. };
  17844. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17845. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17846. if (!options) {
  17847. return shape;
  17848. }
  17849. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17850. };
  17851. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17852. var shape = new CANNON.Plane();
  17853. if (!options) {
  17854. return shape;
  17855. }
  17856. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17857. };
  17858. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17859. var verts = [], faces = [];
  17860. mesh.computeWorldMatrix(true);
  17861. for (var i = 0; i < rawVerts.length; i += 3) {
  17862. var transformed = BABYLON.Vector3.Zero();
  17863. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17864. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17865. }
  17866. for (var j = 0; j < rawFaces.length; j += 3) {
  17867. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17868. }
  17869. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17870. if (!options) {
  17871. return shape;
  17872. }
  17873. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17874. };
  17875. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17876. var index;
  17877. var mat;
  17878. for (index = 0; index < this._physicsMaterials.length; index++) {
  17879. mat = this._physicsMaterials[index];
  17880. if (mat.friction === friction && mat.restitution === restitution) {
  17881. return mat;
  17882. }
  17883. }
  17884. var currentMat = new CANNON.Material();
  17885. currentMat.friction = friction;
  17886. currentMat.restitution = restitution;
  17887. this._physicsMaterials.push(currentMat);
  17888. for (index = 0; index < this._physicsMaterials.length; index++) {
  17889. mat = this._physicsMaterials[index];
  17890. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17891. contactMaterial.contactEquationStiffness = 1e10;
  17892. contactMaterial.contactEquationRegularizationTime = 10;
  17893. this._world.addContactMaterial(contactMaterial);
  17894. }
  17895. return currentMat;
  17896. };
  17897. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  17898. var initialRotation = null;
  17899. if (mesh.rotationQuaternion) {
  17900. initialRotation = mesh.rotationQuaternion.clone();
  17901. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17902. }
  17903. var bbox = mesh.getBoundingInfo().boundingBox;
  17904. var deltaPosition = mesh.position.subtract(bbox.center);
  17905. var material = this._addMaterial(friction, restitution);
  17906. var body = new CANNON.RigidBody(mass, shape, material);
  17907. if (initialRotation) {
  17908. body.quaternion.x = initialRotation.x;
  17909. body.quaternion.z = initialRotation.y;
  17910. body.quaternion.y = initialRotation.z;
  17911. body.quaternion.w = -initialRotation.w;
  17912. }
  17913. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  17914. this._world.add(body);
  17915. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  17916. return body;
  17917. };
  17918. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17919. var compoundShape = new CANNON.Compound();
  17920. for (var index = 0; index < parts.length; index++) {
  17921. var mesh = parts[index].mesh;
  17922. var shape = this.registerMesh(mesh, parts[index].impostor);
  17923. if (index == 0) {
  17924. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  17925. } else {
  17926. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  17927. }
  17928. }
  17929. var initialMesh = parts[0].mesh;
  17930. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  17931. body.parts = parts;
  17932. return body;
  17933. };
  17934. CannonJSPlugin.prototype._unbindBody = function (body) {
  17935. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17936. var registeredMesh = this._registeredMeshes[index];
  17937. if (registeredMesh.body === body) {
  17938. registeredMesh.body = null;
  17939. registeredMesh.delta = 0;
  17940. }
  17941. }
  17942. };
  17943. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  17944. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17945. var registeredMesh = this._registeredMeshes[index];
  17946. if (registeredMesh.mesh === mesh) {
  17947. if (registeredMesh.body) {
  17948. this._world.remove(registeredMesh.body);
  17949. this._unbindBody(registeredMesh.body);
  17950. }
  17951. this._registeredMeshes.splice(index, 1);
  17952. return;
  17953. }
  17954. }
  17955. };
  17956. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17957. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  17958. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  17959. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17960. var registeredMesh = this._registeredMeshes[index];
  17961. if (registeredMesh.mesh === mesh) {
  17962. registeredMesh.body.applyImpulse(impulse, worldPoint);
  17963. return;
  17964. }
  17965. }
  17966. };
  17967. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  17968. var body1 = null, body2 = null;
  17969. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17970. var registeredMesh = this._registeredMeshes[index];
  17971. if (registeredMesh.mesh === mesh1) {
  17972. body1 = registeredMesh.body;
  17973. } else if (registeredMesh.mesh === mesh2) {
  17974. body2 = registeredMesh.body;
  17975. }
  17976. }
  17977. if (!body1 || !body2) {
  17978. return false;
  17979. }
  17980. 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));
  17981. this._world.addConstraint(constraint);
  17982. return true;
  17983. };
  17984. CannonJSPlugin.prototype.dispose = function () {
  17985. while (this._registeredMeshes.length) {
  17986. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17987. }
  17988. };
  17989. CannonJSPlugin.prototype.isSupported = function () {
  17990. return window.CANNON !== undefined;
  17991. };
  17992. return CannonJSPlugin;
  17993. })();
  17994. BABYLON.CannonJSPlugin = CannonJSPlugin;
  17995. })(BABYLON || (BABYLON = {}));
  17996. var __extends = this.__extends || function (d, b) {
  17997. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17998. function __() { this.constructor = d; }
  17999. __.prototype = b.prototype;
  18000. d.prototype = new __();
  18001. };
  18002. var BABYLON;
  18003. (function (BABYLON) {
  18004. var Condition = (function () {
  18005. function Condition(actionManager) {
  18006. this._actionManager = actionManager;
  18007. }
  18008. Condition.prototype.isValid = function () {
  18009. return true;
  18010. };
  18011. Condition.prototype._getProperty = function (propertyPath) {
  18012. return this._actionManager._getProperty(propertyPath);
  18013. };
  18014. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18015. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18016. };
  18017. return Condition;
  18018. })();
  18019. BABYLON.Condition = Condition;
  18020. var ValueCondition = (function (_super) {
  18021. __extends(ValueCondition, _super);
  18022. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18023. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18024. _super.call(this, actionManager);
  18025. this.propertyPath = propertyPath;
  18026. this.value = value;
  18027. this.operator = operator;
  18028. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18029. this._property = this._getProperty(this.propertyPath);
  18030. }
  18031. Object.defineProperty(ValueCondition, "IsEqual", {
  18032. get: function () {
  18033. return ValueCondition._IsEqual;
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. Object.defineProperty(ValueCondition, "IsDifferent", {
  18039. get: function () {
  18040. return ValueCondition._IsDifferent;
  18041. },
  18042. enumerable: true,
  18043. configurable: true
  18044. });
  18045. Object.defineProperty(ValueCondition, "IsGreater", {
  18046. get: function () {
  18047. return ValueCondition._IsGreater;
  18048. },
  18049. enumerable: true,
  18050. configurable: true
  18051. });
  18052. Object.defineProperty(ValueCondition, "IsLesser", {
  18053. get: function () {
  18054. return ValueCondition._IsLesser;
  18055. },
  18056. enumerable: true,
  18057. configurable: true
  18058. });
  18059. ValueCondition.prototype.isValid = function () {
  18060. switch (this.operator) {
  18061. case ValueCondition.IsGreater:
  18062. return this._target[this._property] > this.value;
  18063. case ValueCondition.IsLesser:
  18064. return this._target[this._property] < this.value;
  18065. case ValueCondition.IsEqual:
  18066. case ValueCondition.IsDifferent:
  18067. var check;
  18068. if (this.value.equals) {
  18069. check = this.value.equals(this._target[this._property]);
  18070. } else {
  18071. check = this.value === this._target[this._property];
  18072. }
  18073. return this.operator === ValueCondition.IsEqual ? check : !check;
  18074. }
  18075. return false;
  18076. };
  18077. ValueCondition._IsEqual = 0;
  18078. ValueCondition._IsDifferent = 1;
  18079. ValueCondition._IsGreater = 2;
  18080. ValueCondition._IsLesser = 3;
  18081. return ValueCondition;
  18082. })(Condition);
  18083. BABYLON.ValueCondition = ValueCondition;
  18084. var PredicateCondition = (function (_super) {
  18085. __extends(PredicateCondition, _super);
  18086. function PredicateCondition(actionManager, predicate) {
  18087. _super.call(this, actionManager);
  18088. this.predicate = predicate;
  18089. }
  18090. PredicateCondition.prototype.isValid = function () {
  18091. return this.predicate();
  18092. };
  18093. return PredicateCondition;
  18094. })(Condition);
  18095. BABYLON.PredicateCondition = PredicateCondition;
  18096. var StateCondition = (function (_super) {
  18097. __extends(StateCondition, _super);
  18098. function StateCondition(actionManager, target, value) {
  18099. _super.call(this, actionManager);
  18100. this.value = value;
  18101. this._target = target;
  18102. }
  18103. StateCondition.prototype.isValid = function () {
  18104. return this._target.state === this.value;
  18105. };
  18106. return StateCondition;
  18107. })(Condition);
  18108. BABYLON.StateCondition = StateCondition;
  18109. })(BABYLON || (BABYLON = {}));
  18110. var BABYLON;
  18111. (function (BABYLON) {
  18112. var Action = (function () {
  18113. function Action(triggerOptions, condition) {
  18114. this.triggerOptions = triggerOptions;
  18115. if (triggerOptions.parameter) {
  18116. this.trigger = triggerOptions.trigger;
  18117. this._triggerParameter = triggerOptions.parameter;
  18118. } else {
  18119. this.trigger = triggerOptions;
  18120. }
  18121. this._nextActiveAction = this;
  18122. this._condition = condition;
  18123. }
  18124. Action.prototype._prepare = function () {
  18125. };
  18126. Action.prototype.getTriggerParameter = function () {
  18127. return this._triggerParameter;
  18128. };
  18129. Action.prototype._executeCurrent = function (evt) {
  18130. if (this._condition) {
  18131. var currentRenderId = this._actionManager.getScene().getRenderId();
  18132. if (this._condition._evaluationId === currentRenderId) {
  18133. if (!this._condition._currentResult) {
  18134. return;
  18135. }
  18136. } else {
  18137. this._condition._evaluationId = currentRenderId;
  18138. if (!this._condition.isValid()) {
  18139. this._condition._currentResult = false;
  18140. return;
  18141. }
  18142. this._condition._currentResult = true;
  18143. }
  18144. }
  18145. this._nextActiveAction.execute(evt);
  18146. if (this._nextActiveAction._child) {
  18147. this._nextActiveAction = this._nextActiveAction._child;
  18148. } else {
  18149. this._nextActiveAction = this;
  18150. }
  18151. };
  18152. Action.prototype.execute = function (evt) {
  18153. };
  18154. Action.prototype.then = function (action) {
  18155. this._child = action;
  18156. action._actionManager = this._actionManager;
  18157. action._prepare();
  18158. return action;
  18159. };
  18160. Action.prototype._getProperty = function (propertyPath) {
  18161. return this._actionManager._getProperty(propertyPath);
  18162. };
  18163. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18164. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18165. };
  18166. return Action;
  18167. })();
  18168. BABYLON.Action = Action;
  18169. })(BABYLON || (BABYLON = {}));
  18170. var BABYLON;
  18171. (function (BABYLON) {
  18172. var ActionEvent = (function () {
  18173. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18174. this.source = source;
  18175. this.pointerX = pointerX;
  18176. this.pointerY = pointerY;
  18177. this.meshUnderPointer = meshUnderPointer;
  18178. this.sourceEvent = sourceEvent;
  18179. }
  18180. ActionEvent.CreateNew = function (source) {
  18181. var scene = source.getScene();
  18182. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18183. };
  18184. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18185. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18186. };
  18187. return ActionEvent;
  18188. })();
  18189. BABYLON.ActionEvent = ActionEvent;
  18190. var ActionManager = (function () {
  18191. function ActionManager(scene) {
  18192. this.actions = new Array();
  18193. this._scene = scene;
  18194. scene._actionManagers.push(this);
  18195. }
  18196. Object.defineProperty(ActionManager, "NothingTrigger", {
  18197. get: function () {
  18198. return ActionManager._NothingTrigger;
  18199. },
  18200. enumerable: true,
  18201. configurable: true
  18202. });
  18203. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18204. get: function () {
  18205. return ActionManager._OnPickTrigger;
  18206. },
  18207. enumerable: true,
  18208. configurable: true
  18209. });
  18210. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18211. get: function () {
  18212. return ActionManager._OnLeftPickTrigger;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18218. get: function () {
  18219. return ActionManager._OnRightPickTrigger;
  18220. },
  18221. enumerable: true,
  18222. configurable: true
  18223. });
  18224. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18225. get: function () {
  18226. return ActionManager._OnCenterPickTrigger;
  18227. },
  18228. enumerable: true,
  18229. configurable: true
  18230. });
  18231. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18232. get: function () {
  18233. return ActionManager._OnPointerOverTrigger;
  18234. },
  18235. enumerable: true,
  18236. configurable: true
  18237. });
  18238. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18239. get: function () {
  18240. return ActionManager._OnPointerOutTrigger;
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18246. get: function () {
  18247. return ActionManager._OnEveryFrameTrigger;
  18248. },
  18249. enumerable: true,
  18250. configurable: true
  18251. });
  18252. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18253. get: function () {
  18254. return ActionManager._OnIntersectionEnterTrigger;
  18255. },
  18256. enumerable: true,
  18257. configurable: true
  18258. });
  18259. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18260. get: function () {
  18261. return ActionManager._OnIntersectionExitTrigger;
  18262. },
  18263. enumerable: true,
  18264. configurable: true
  18265. });
  18266. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18267. get: function () {
  18268. return ActionManager._OnKeyDownTrigger;
  18269. },
  18270. enumerable: true,
  18271. configurable: true
  18272. });
  18273. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18274. get: function () {
  18275. return ActionManager._OnKeyUpTrigger;
  18276. },
  18277. enumerable: true,
  18278. configurable: true
  18279. });
  18280. ActionManager.prototype.dispose = function () {
  18281. var index = this._scene._actionManagers.indexOf(this);
  18282. if (index > -1) {
  18283. this._scene._actionManagers.splice(index, 1);
  18284. }
  18285. };
  18286. ActionManager.prototype.getScene = function () {
  18287. return this._scene;
  18288. };
  18289. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18290. for (var index = 0; index < this.actions.length; index++) {
  18291. var action = this.actions[index];
  18292. if (triggers.indexOf(action.trigger) > -1) {
  18293. return true;
  18294. }
  18295. }
  18296. return false;
  18297. };
  18298. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18299. get: function () {
  18300. for (var index = 0; index < this.actions.length; index++) {
  18301. var action = this.actions[index];
  18302. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18303. return true;
  18304. }
  18305. }
  18306. return false;
  18307. },
  18308. enumerable: true,
  18309. configurable: true
  18310. });
  18311. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18312. get: function () {
  18313. for (var index = 0; index < this.actions.length; index++) {
  18314. var action = this.actions[index];
  18315. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18316. return true;
  18317. }
  18318. }
  18319. return false;
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. ActionManager.prototype.registerAction = function (action) {
  18325. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18326. if (this.getScene().actionManager !== this) {
  18327. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18328. return null;
  18329. }
  18330. }
  18331. this.actions.push(action);
  18332. action._actionManager = this;
  18333. action._prepare();
  18334. return action;
  18335. };
  18336. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18337. for (var index = 0; index < this.actions.length; index++) {
  18338. var action = this.actions[index];
  18339. if (action.trigger === trigger) {
  18340. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18341. var parameter = action.getTriggerParameter();
  18342. if (parameter) {
  18343. if (evt.sourceEvent.key !== parameter) {
  18344. continue;
  18345. }
  18346. }
  18347. }
  18348. action._executeCurrent(evt);
  18349. }
  18350. }
  18351. };
  18352. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18353. var properties = propertyPath.split(".");
  18354. for (var index = 0; index < properties.length - 1; index++) {
  18355. target = target[properties[index]];
  18356. }
  18357. return target;
  18358. };
  18359. ActionManager.prototype._getProperty = function (propertyPath) {
  18360. var properties = propertyPath.split(".");
  18361. return properties[properties.length - 1];
  18362. };
  18363. ActionManager._NothingTrigger = 0;
  18364. ActionManager._OnPickTrigger = 1;
  18365. ActionManager._OnLeftPickTrigger = 2;
  18366. ActionManager._OnRightPickTrigger = 3;
  18367. ActionManager._OnCenterPickTrigger = 4;
  18368. ActionManager._OnPointerOverTrigger = 5;
  18369. ActionManager._OnPointerOutTrigger = 6;
  18370. ActionManager._OnEveryFrameTrigger = 7;
  18371. ActionManager._OnIntersectionEnterTrigger = 8;
  18372. ActionManager._OnIntersectionExitTrigger = 9;
  18373. ActionManager._OnKeyDownTrigger = 10;
  18374. ActionManager._OnKeyUpTrigger = 11;
  18375. return ActionManager;
  18376. })();
  18377. BABYLON.ActionManager = ActionManager;
  18378. })(BABYLON || (BABYLON = {}));
  18379. var __extends = this.__extends || function (d, b) {
  18380. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18381. function __() { this.constructor = d; }
  18382. __.prototype = b.prototype;
  18383. d.prototype = new __();
  18384. };
  18385. var BABYLON;
  18386. (function (BABYLON) {
  18387. var InterpolateValueAction = (function (_super) {
  18388. __extends(InterpolateValueAction, _super);
  18389. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18390. if (typeof duration === "undefined") { duration = 1000; }
  18391. _super.call(this, triggerOptions, condition);
  18392. this.propertyPath = propertyPath;
  18393. this.value = value;
  18394. this.duration = duration;
  18395. this.stopOtherAnimations = stopOtherAnimations;
  18396. this._target = target;
  18397. }
  18398. InterpolateValueAction.prototype._prepare = function () {
  18399. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18400. this._property = this._getProperty(this.propertyPath);
  18401. };
  18402. InterpolateValueAction.prototype.execute = function () {
  18403. var scene = this._actionManager.getScene();
  18404. var keys = [
  18405. {
  18406. frame: 0,
  18407. value: this._target[this._property]
  18408. }, {
  18409. frame: 100,
  18410. value: this.value
  18411. }
  18412. ];
  18413. var dataType;
  18414. if (typeof this.value === "number") {
  18415. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18416. } else if (this.value instanceof BABYLON.Color3) {
  18417. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18418. } else if (this.value instanceof BABYLON.Vector3) {
  18419. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18420. } else if (this.value instanceof BABYLON.Matrix) {
  18421. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18422. } else if (this.value instanceof BABYLON.Quaternion) {
  18423. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18424. } else {
  18425. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18426. return;
  18427. }
  18428. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18429. animation.setKeys(keys);
  18430. if (this.stopOtherAnimations) {
  18431. scene.stopAnimation(this._target);
  18432. }
  18433. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18434. };
  18435. return InterpolateValueAction;
  18436. })(BABYLON.Action);
  18437. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18438. })(BABYLON || (BABYLON = {}));
  18439. var __extends = this.__extends || function (d, b) {
  18440. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18441. function __() { this.constructor = d; }
  18442. __.prototype = b.prototype;
  18443. d.prototype = new __();
  18444. };
  18445. var BABYLON;
  18446. (function (BABYLON) {
  18447. var SwitchBooleanAction = (function (_super) {
  18448. __extends(SwitchBooleanAction, _super);
  18449. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18450. _super.call(this, triggerOptions, condition);
  18451. this.propertyPath = propertyPath;
  18452. this._target = target;
  18453. }
  18454. SwitchBooleanAction.prototype._prepare = function () {
  18455. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18456. this._property = this._getProperty(this.propertyPath);
  18457. };
  18458. SwitchBooleanAction.prototype.execute = function () {
  18459. this._target[this._property] = !this._target[this._property];
  18460. };
  18461. return SwitchBooleanAction;
  18462. })(BABYLON.Action);
  18463. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18464. var SetStateAction = (function (_super) {
  18465. __extends(SetStateAction, _super);
  18466. function SetStateAction(triggerOptions, target, value, condition) {
  18467. _super.call(this, triggerOptions, condition);
  18468. this.value = value;
  18469. this._target = target;
  18470. }
  18471. SetStateAction.prototype.execute = function () {
  18472. this._target.state = this.value;
  18473. };
  18474. return SetStateAction;
  18475. })(BABYLON.Action);
  18476. BABYLON.SetStateAction = SetStateAction;
  18477. var SetValueAction = (function (_super) {
  18478. __extends(SetValueAction, _super);
  18479. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18480. _super.call(this, triggerOptions, condition);
  18481. this.propertyPath = propertyPath;
  18482. this.value = value;
  18483. this._target = target;
  18484. }
  18485. SetValueAction.prototype._prepare = function () {
  18486. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18487. this._property = this._getProperty(this.propertyPath);
  18488. };
  18489. SetValueAction.prototype.execute = function () {
  18490. this._target[this._property] = this.value;
  18491. };
  18492. return SetValueAction;
  18493. })(BABYLON.Action);
  18494. BABYLON.SetValueAction = SetValueAction;
  18495. var IncrementValueAction = (function (_super) {
  18496. __extends(IncrementValueAction, _super);
  18497. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18498. _super.call(this, triggerOptions, condition);
  18499. this.propertyPath = propertyPath;
  18500. this.value = value;
  18501. this._target = target;
  18502. }
  18503. IncrementValueAction.prototype._prepare = function () {
  18504. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18505. this._property = this._getProperty(this.propertyPath);
  18506. if (typeof this._target[this._property] !== "number") {
  18507. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18508. }
  18509. };
  18510. IncrementValueAction.prototype.execute = function () {
  18511. this._target[this._property] += this.value;
  18512. };
  18513. return IncrementValueAction;
  18514. })(BABYLON.Action);
  18515. BABYLON.IncrementValueAction = IncrementValueAction;
  18516. var PlayAnimationAction = (function (_super) {
  18517. __extends(PlayAnimationAction, _super);
  18518. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18519. _super.call(this, triggerOptions, condition);
  18520. this.from = from;
  18521. this.to = to;
  18522. this.loop = loop;
  18523. this._target = target;
  18524. }
  18525. PlayAnimationAction.prototype._prepare = function () {
  18526. };
  18527. PlayAnimationAction.prototype.execute = function () {
  18528. var scene = this._actionManager.getScene();
  18529. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18530. };
  18531. return PlayAnimationAction;
  18532. })(BABYLON.Action);
  18533. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18534. var StopAnimationAction = (function (_super) {
  18535. __extends(StopAnimationAction, _super);
  18536. function StopAnimationAction(triggerOptions, target, condition) {
  18537. _super.call(this, triggerOptions, condition);
  18538. this._target = target;
  18539. }
  18540. StopAnimationAction.prototype._prepare = function () {
  18541. };
  18542. StopAnimationAction.prototype.execute = function () {
  18543. var scene = this._actionManager.getScene();
  18544. scene.stopAnimation(this._target);
  18545. };
  18546. return StopAnimationAction;
  18547. })(BABYLON.Action);
  18548. BABYLON.StopAnimationAction = StopAnimationAction;
  18549. var DoNothingAction = (function (_super) {
  18550. __extends(DoNothingAction, _super);
  18551. function DoNothingAction(triggerOptions, condition) {
  18552. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18553. _super.call(this, triggerOptions, condition);
  18554. }
  18555. DoNothingAction.prototype.execute = function () {
  18556. };
  18557. return DoNothingAction;
  18558. })(BABYLON.Action);
  18559. BABYLON.DoNothingAction = DoNothingAction;
  18560. var CombineAction = (function (_super) {
  18561. __extends(CombineAction, _super);
  18562. function CombineAction(triggerOptions, children, condition) {
  18563. _super.call(this, triggerOptions, condition);
  18564. this.children = children;
  18565. }
  18566. CombineAction.prototype._prepare = function () {
  18567. for (var index = 0; index < this.children.length; index++) {
  18568. this.children[index]._actionManager = this._actionManager;
  18569. this.children[index]._prepare();
  18570. }
  18571. };
  18572. CombineAction.prototype.execute = function (evt) {
  18573. for (var index = 0; index < this.children.length; index++) {
  18574. this.children[index].execute(evt);
  18575. }
  18576. };
  18577. return CombineAction;
  18578. })(BABYLON.Action);
  18579. BABYLON.CombineAction = CombineAction;
  18580. var ExecuteCodeAction = (function (_super) {
  18581. __extends(ExecuteCodeAction, _super);
  18582. function ExecuteCodeAction(triggerOptions, func, condition) {
  18583. _super.call(this, triggerOptions, condition);
  18584. this.func = func;
  18585. }
  18586. ExecuteCodeAction.prototype.execute = function (evt) {
  18587. this.func(evt);
  18588. };
  18589. return ExecuteCodeAction;
  18590. })(BABYLON.Action);
  18591. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18592. var SetParentAction = (function (_super) {
  18593. __extends(SetParentAction, _super);
  18594. function SetParentAction(triggerOptions, target, parent, condition) {
  18595. _super.call(this, triggerOptions, condition);
  18596. this._target = target;
  18597. this._parent = parent;
  18598. }
  18599. SetParentAction.prototype._prepare = function () {
  18600. };
  18601. SetParentAction.prototype.execute = function () {
  18602. if (this._target.parent === this._parent) {
  18603. return;
  18604. }
  18605. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18606. invertParentWorldMatrix.invert();
  18607. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18608. this._target.parent = this._parent;
  18609. };
  18610. return SetParentAction;
  18611. })(BABYLON.Action);
  18612. BABYLON.SetParentAction = SetParentAction;
  18613. })(BABYLON || (BABYLON = {}));
  18614. var __extends = this.__extends || function (d, b) {
  18615. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18616. function __() { this.constructor = d; }
  18617. __.prototype = b.prototype;
  18618. d.prototype = new __();
  18619. };
  18620. var BABYLON;
  18621. (function (BABYLON) {
  18622. var Geometry = (function () {
  18623. function Geometry(id, scene, vertexData, updatable, mesh) {
  18624. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18625. this._totalVertices = 0;
  18626. this._indices = [];
  18627. this.id = id;
  18628. this._engine = scene.getEngine();
  18629. this._meshes = [];
  18630. this._scene = scene;
  18631. if (vertexData) {
  18632. this.setAllVerticesData(vertexData, updatable);
  18633. } else {
  18634. this._totalVertices = 0;
  18635. this._indices = [];
  18636. }
  18637. if (mesh) {
  18638. this.applyToMesh(mesh);
  18639. }
  18640. }
  18641. Geometry.prototype.getScene = function () {
  18642. return this._scene;
  18643. };
  18644. Geometry.prototype.getEngine = function () {
  18645. return this._engine;
  18646. };
  18647. Geometry.prototype.isReady = function () {
  18648. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18649. };
  18650. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18651. vertexData.applyToGeometry(this, updatable);
  18652. };
  18653. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18654. this._vertexBuffers = this._vertexBuffers || {};
  18655. if (this._vertexBuffers[kind]) {
  18656. this._vertexBuffers[kind].dispose();
  18657. }
  18658. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18659. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18660. var stride = this._vertexBuffers[kind].getStrideSize();
  18661. this._totalVertices = data.length / stride;
  18662. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18663. var meshes = this._meshes;
  18664. var numOfMeshes = meshes.length;
  18665. for (var index = 0; index < numOfMeshes; index++) {
  18666. var mesh = meshes[index];
  18667. mesh._resetPointsArrayCache();
  18668. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18669. mesh._createGlobalSubMesh();
  18670. mesh.computeWorldMatrix(true);
  18671. }
  18672. }
  18673. };
  18674. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18675. var vertexBuffer = this.getVertexBuffer(kind);
  18676. if (!vertexBuffer) {
  18677. return;
  18678. }
  18679. vertexBuffer.update(data);
  18680. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18681. var extend;
  18682. if (updateExtends) {
  18683. var stride = vertexBuffer.getStrideSize();
  18684. this._totalVertices = data.length / stride;
  18685. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18686. }
  18687. var meshes = this._meshes;
  18688. var numOfMeshes = meshes.length;
  18689. for (var index = 0; index < numOfMeshes; index++) {
  18690. var mesh = meshes[index];
  18691. mesh._resetPointsArrayCache();
  18692. if (updateExtends) {
  18693. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18694. }
  18695. }
  18696. }
  18697. };
  18698. Geometry.prototype.getTotalVertices = function () {
  18699. if (!this.isReady()) {
  18700. return 0;
  18701. }
  18702. return this._totalVertices;
  18703. };
  18704. Geometry.prototype.getVerticesData = function (kind) {
  18705. var vertexBuffer = this.getVertexBuffer(kind);
  18706. if (!vertexBuffer) {
  18707. return null;
  18708. }
  18709. return vertexBuffer.getData();
  18710. };
  18711. Geometry.prototype.getVertexBuffer = function (kind) {
  18712. if (!this.isReady()) {
  18713. return null;
  18714. }
  18715. return this._vertexBuffers[kind];
  18716. };
  18717. Geometry.prototype.getVertexBuffers = function () {
  18718. if (!this.isReady()) {
  18719. return null;
  18720. }
  18721. return this._vertexBuffers;
  18722. };
  18723. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18724. if (!this._vertexBuffers) {
  18725. if (this._delayInfo) {
  18726. return this._delayInfo.indexOf(kind) !== -1;
  18727. }
  18728. return false;
  18729. }
  18730. return this._vertexBuffers[kind] !== undefined;
  18731. };
  18732. Geometry.prototype.getVerticesDataKinds = function () {
  18733. var result = [];
  18734. if (!this._vertexBuffers && this._delayInfo) {
  18735. for (var kind in this._delayInfo) {
  18736. result.push(kind);
  18737. }
  18738. } else {
  18739. for (kind in this._vertexBuffers) {
  18740. result.push(kind);
  18741. }
  18742. }
  18743. return result;
  18744. };
  18745. Geometry.prototype.setIndices = function (indices) {
  18746. if (this._indexBuffer) {
  18747. this._engine._releaseBuffer(this._indexBuffer);
  18748. }
  18749. this._indices = indices;
  18750. if (this._meshes.length !== 0 && this._indices) {
  18751. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18752. }
  18753. var meshes = this._meshes;
  18754. var numOfMeshes = meshes.length;
  18755. for (var index = 0; index < numOfMeshes; index++) {
  18756. meshes[index]._createGlobalSubMesh();
  18757. }
  18758. };
  18759. Geometry.prototype.getTotalIndices = function () {
  18760. if (!this.isReady()) {
  18761. return 0;
  18762. }
  18763. return this._indices.length;
  18764. };
  18765. Geometry.prototype.getIndices = function () {
  18766. if (!this.isReady()) {
  18767. return null;
  18768. }
  18769. return this._indices;
  18770. };
  18771. Geometry.prototype.getIndexBuffer = function () {
  18772. if (!this.isReady()) {
  18773. return null;
  18774. }
  18775. return this._indexBuffer;
  18776. };
  18777. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18778. var meshes = this._meshes;
  18779. var index = meshes.indexOf(mesh);
  18780. if (index === -1) {
  18781. return;
  18782. }
  18783. for (var kind in this._vertexBuffers) {
  18784. this._vertexBuffers[kind].dispose();
  18785. }
  18786. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18787. this._indexBuffer = null;
  18788. }
  18789. meshes.splice(index, 1);
  18790. mesh._geometry = null;
  18791. if (meshes.length == 0 && shouldDispose) {
  18792. this.dispose();
  18793. }
  18794. };
  18795. Geometry.prototype.applyToMesh = function (mesh) {
  18796. if (mesh._geometry === this) {
  18797. return;
  18798. }
  18799. var previousGeometry = mesh._geometry;
  18800. if (previousGeometry) {
  18801. previousGeometry.releaseForMesh(mesh);
  18802. }
  18803. var meshes = this._meshes;
  18804. mesh._geometry = this;
  18805. this._scene.pushGeometry(this);
  18806. meshes.push(mesh);
  18807. if (this.isReady()) {
  18808. this._applyToMesh(mesh);
  18809. } else {
  18810. mesh._boundingInfo = this._boundingInfo;
  18811. }
  18812. };
  18813. Geometry.prototype._applyToMesh = function (mesh) {
  18814. var numOfMeshes = this._meshes.length;
  18815. for (var kind in this._vertexBuffers) {
  18816. if (numOfMeshes === 1) {
  18817. this._vertexBuffers[kind].create();
  18818. }
  18819. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18820. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18821. mesh._resetPointsArrayCache();
  18822. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18823. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18824. mesh._createGlobalSubMesh();
  18825. }
  18826. }
  18827. if (numOfMeshes === 1 && this._indices) {
  18828. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18829. }
  18830. if (this._indexBuffer) {
  18831. this._indexBuffer.references = numOfMeshes;
  18832. }
  18833. };
  18834. Geometry.prototype.load = function (scene, onLoaded) {
  18835. var _this = this;
  18836. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18837. return;
  18838. }
  18839. if (this.isReady()) {
  18840. if (onLoaded) {
  18841. onLoaded();
  18842. }
  18843. return;
  18844. }
  18845. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18846. scene._addPendingData(this);
  18847. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18848. _this._delayLoadingFunction(JSON.parse(data), _this);
  18849. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18850. _this._delayInfo = [];
  18851. scene._removePendingData(_this);
  18852. var meshes = _this._meshes;
  18853. var numOfMeshes = meshes.length;
  18854. for (var index = 0; index < numOfMeshes; index++) {
  18855. _this._applyToMesh(meshes[index]);
  18856. }
  18857. if (onLoaded) {
  18858. onLoaded();
  18859. }
  18860. }, function () {
  18861. }, scene.database);
  18862. };
  18863. Geometry.prototype.dispose = function () {
  18864. var meshes = this._meshes;
  18865. var numOfMeshes = meshes.length;
  18866. for (var index = 0; index < numOfMeshes; index++) {
  18867. this.releaseForMesh(meshes[index]);
  18868. }
  18869. this._meshes = [];
  18870. for (var kind in this._vertexBuffers) {
  18871. this._vertexBuffers[kind].dispose();
  18872. }
  18873. this._vertexBuffers = [];
  18874. this._totalVertices = 0;
  18875. if (this._indexBuffer) {
  18876. this._engine._releaseBuffer(this._indexBuffer);
  18877. }
  18878. this._indexBuffer = null;
  18879. this._indices = [];
  18880. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18881. this.delayLoadingFile = null;
  18882. this._delayLoadingFunction = null;
  18883. this._delayInfo = [];
  18884. this._boundingInfo = null;
  18885. var geometries = this._scene.getGeometries();
  18886. index = geometries.indexOf(this);
  18887. if (index > -1) {
  18888. geometries.splice(index, 1);
  18889. }
  18890. };
  18891. Geometry.prototype.copy = function (id) {
  18892. var vertexData = new BABYLON.VertexData();
  18893. vertexData.indices = [];
  18894. var indices = this.getIndices();
  18895. for (var index = 0; index < indices.length; index++) {
  18896. vertexData.indices.push(indices[index]);
  18897. }
  18898. var updatable = false;
  18899. var stopChecking = false;
  18900. for (var kind in this._vertexBuffers) {
  18901. vertexData.set(this.getVerticesData(kind), kind);
  18902. if (!stopChecking) {
  18903. updatable = this.getVertexBuffer(kind).isUpdatable();
  18904. stopChecking = !updatable;
  18905. }
  18906. }
  18907. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  18908. geometry.delayLoadState = this.delayLoadState;
  18909. geometry.delayLoadingFile = this.delayLoadingFile;
  18910. geometry._delayLoadingFunction = this._delayLoadingFunction;
  18911. for (kind in this._delayInfo) {
  18912. geometry._delayInfo = geometry._delayInfo || [];
  18913. geometry._delayInfo.push(kind);
  18914. }
  18915. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  18916. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18917. return geometry;
  18918. };
  18919. Geometry.ExtractFromMesh = function (mesh, id) {
  18920. var geometry = mesh._geometry;
  18921. if (!geometry) {
  18922. return null;
  18923. }
  18924. return geometry.copy(id);
  18925. };
  18926. Geometry.RandomId = function () {
  18927. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  18928. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  18929. return v.toString(16);
  18930. });
  18931. };
  18932. return Geometry;
  18933. })();
  18934. BABYLON.Geometry = Geometry;
  18935. (function (Geometry) {
  18936. (function (Primitives) {
  18937. var _Primitive = (function (_super) {
  18938. __extends(_Primitive, _super);
  18939. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  18940. this._beingRegenerated = true;
  18941. this._canBeRegenerated = canBeRegenerated;
  18942. _super.call(this, id, scene, vertexData, false, mesh);
  18943. this._beingRegenerated = false;
  18944. }
  18945. _Primitive.prototype.canBeRegenerated = function () {
  18946. return this._canBeRegenerated;
  18947. };
  18948. _Primitive.prototype.regenerate = function () {
  18949. if (!this._canBeRegenerated) {
  18950. return;
  18951. }
  18952. this._beingRegenerated = true;
  18953. this.setAllVerticesData(this._regenerateVertexData(), false);
  18954. this._beingRegenerated = false;
  18955. };
  18956. _Primitive.prototype.asNewGeometry = function (id) {
  18957. return _super.prototype.copy.call(this, id);
  18958. };
  18959. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  18960. if (!this._beingRegenerated) {
  18961. return;
  18962. }
  18963. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  18964. };
  18965. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  18966. if (!this._beingRegenerated) {
  18967. return;
  18968. }
  18969. _super.prototype.setVerticesData.call(this, kind, data, false);
  18970. };
  18971. _Primitive.prototype._regenerateVertexData = function () {
  18972. throw new Error("Abstract method");
  18973. };
  18974. _Primitive.prototype.copy = function (id) {
  18975. throw new Error("Must be overriden in sub-classes.");
  18976. };
  18977. return _Primitive;
  18978. })(Geometry);
  18979. Primitives._Primitive = _Primitive;
  18980. var Box = (function (_super) {
  18981. __extends(Box, _super);
  18982. function Box(id, scene, size, canBeRegenerated, mesh) {
  18983. this.size = size;
  18984. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18985. }
  18986. Box.prototype._regenerateVertexData = function () {
  18987. return BABYLON.VertexData.CreateBox(this.size);
  18988. };
  18989. Box.prototype.copy = function (id) {
  18990. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  18991. };
  18992. return Box;
  18993. })(_Primitive);
  18994. Primitives.Box = Box;
  18995. var Sphere = (function (_super) {
  18996. __extends(Sphere, _super);
  18997. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  18998. this.segments = segments;
  18999. this.diameter = diameter;
  19000. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19001. }
  19002. Sphere.prototype._regenerateVertexData = function () {
  19003. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19004. };
  19005. Sphere.prototype.copy = function (id) {
  19006. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19007. };
  19008. return Sphere;
  19009. })(_Primitive);
  19010. Primitives.Sphere = Sphere;
  19011. var Cylinder = (function (_super) {
  19012. __extends(Cylinder, _super);
  19013. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19014. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19015. this.height = height;
  19016. this.diameterTop = diameterTop;
  19017. this.diameterBottom = diameterBottom;
  19018. this.tessellation = tessellation;
  19019. this.subdivisions = subdivisions;
  19020. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19021. }
  19022. Cylinder.prototype._regenerateVertexData = function () {
  19023. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19024. };
  19025. Cylinder.prototype.copy = function (id) {
  19026. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19027. };
  19028. return Cylinder;
  19029. })(_Primitive);
  19030. Primitives.Cylinder = Cylinder;
  19031. var Torus = (function (_super) {
  19032. __extends(Torus, _super);
  19033. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19034. this.diameter = diameter;
  19035. this.thickness = thickness;
  19036. this.tessellation = tessellation;
  19037. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19038. }
  19039. Torus.prototype._regenerateVertexData = function () {
  19040. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19041. };
  19042. Torus.prototype.copy = function (id) {
  19043. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19044. };
  19045. return Torus;
  19046. })(_Primitive);
  19047. Primitives.Torus = Torus;
  19048. var Ground = (function (_super) {
  19049. __extends(Ground, _super);
  19050. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19051. this.width = width;
  19052. this.height = height;
  19053. this.subdivisions = subdivisions;
  19054. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19055. }
  19056. Ground.prototype._regenerateVertexData = function () {
  19057. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19058. };
  19059. Ground.prototype.copy = function (id) {
  19060. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19061. };
  19062. return Ground;
  19063. })(_Primitive);
  19064. Primitives.Ground = Ground;
  19065. var TiledGround = (function (_super) {
  19066. __extends(TiledGround, _super);
  19067. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19068. this.xmin = xmin;
  19069. this.zmin = zmin;
  19070. this.xmax = xmax;
  19071. this.zmax = zmax;
  19072. this.subdivisions = subdivisions;
  19073. this.precision = precision;
  19074. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19075. }
  19076. TiledGround.prototype._regenerateVertexData = function () {
  19077. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19078. };
  19079. TiledGround.prototype.copy = function (id) {
  19080. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19081. };
  19082. return TiledGround;
  19083. })(_Primitive);
  19084. Primitives.TiledGround = TiledGround;
  19085. var Plane = (function (_super) {
  19086. __extends(Plane, _super);
  19087. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19088. this.size = size;
  19089. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19090. }
  19091. Plane.prototype._regenerateVertexData = function () {
  19092. return BABYLON.VertexData.CreatePlane(this.size);
  19093. };
  19094. Plane.prototype.copy = function (id) {
  19095. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19096. };
  19097. return Plane;
  19098. })(_Primitive);
  19099. Primitives.Plane = Plane;
  19100. var TorusKnot = (function (_super) {
  19101. __extends(TorusKnot, _super);
  19102. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19103. this.radius = radius;
  19104. this.tube = tube;
  19105. this.radialSegments = radialSegments;
  19106. this.tubularSegments = tubularSegments;
  19107. this.p = p;
  19108. this.q = q;
  19109. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19110. }
  19111. TorusKnot.prototype._regenerateVertexData = function () {
  19112. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19113. };
  19114. TorusKnot.prototype.copy = function (id) {
  19115. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19116. };
  19117. return TorusKnot;
  19118. })(_Primitive);
  19119. Primitives.TorusKnot = TorusKnot;
  19120. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19121. var Primitives = Geometry.Primitives;
  19122. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19123. var Geometry = BABYLON.Geometry;
  19124. })(BABYLON || (BABYLON = {}));
  19125. var __extends = this.__extends || function (d, b) {
  19126. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19127. function __() { this.constructor = d; }
  19128. __.prototype = b.prototype;
  19129. d.prototype = new __();
  19130. };
  19131. var BABYLON;
  19132. (function (BABYLON) {
  19133. var Gamepads = (function () {
  19134. function Gamepads(ongamedpadconnected) {
  19135. var _this = this;
  19136. this.babylonGamepads = [];
  19137. this.oneGamepadConnected = false;
  19138. this.isMonitoring = false;
  19139. this.gamepadEventSupported = 'GamepadEvent' in window;
  19140. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19141. 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=";
  19142. this._callbackGamepadConnected = ongamedpadconnected;
  19143. if (this.gamepadSupportAvailable) {
  19144. if (this.gamepadEventSupported) {
  19145. window.addEventListener('gamepadconnected', function (evt) {
  19146. _this._onGamepadConnected(evt);
  19147. }, false);
  19148. window.addEventListener('gamepaddisconnected', function (evt) {
  19149. _this._onGamepadDisconnected(evt);
  19150. }, false);
  19151. } else {
  19152. this._startMonitoringGamepads();
  19153. }
  19154. if (!this.oneGamepadConnected) {
  19155. this._insertGamepadDOMInstructions();
  19156. }
  19157. } else {
  19158. this._insertGamepadDOMNotSupported();
  19159. }
  19160. }
  19161. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19162. Gamepads.gamepadDOMInfo = document.createElement("div");
  19163. var buttonAImage = document.createElement("img");
  19164. buttonAImage.src = this.buttonADataURL;
  19165. var spanMessage = document.createElement("span");
  19166. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19167. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19168. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19169. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19170. Gamepads.gamepadDOMInfo.style.width = "100%";
  19171. Gamepads.gamepadDOMInfo.style.height = "48px";
  19172. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19173. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19174. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19175. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19176. buttonAImage.style.position = "relative";
  19177. buttonAImage.style.bottom = "8px";
  19178. spanMessage.style.position = "relative";
  19179. spanMessage.style.fontSize = "32px";
  19180. spanMessage.style.bottom = "32px";
  19181. spanMessage.style.color = "green";
  19182. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19183. };
  19184. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19185. Gamepads.gamepadDOMInfo = document.createElement("div");
  19186. var spanMessage = document.createElement("span");
  19187. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19188. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19189. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19190. Gamepads.gamepadDOMInfo.style.width = "100%";
  19191. Gamepads.gamepadDOMInfo.style.height = "40px";
  19192. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19193. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19194. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19195. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19196. spanMessage.style.position = "relative";
  19197. spanMessage.style.fontSize = "32px";
  19198. spanMessage.style.color = "red";
  19199. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19200. };
  19201. Gamepads.prototype.dispose = function () {
  19202. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19203. };
  19204. Gamepads.prototype._onGamepadConnected = function (evt) {
  19205. var newGamepad = this._addNewGamepad(evt.gamepad);
  19206. if (this._callbackGamepadConnected)
  19207. this._callbackGamepadConnected(newGamepad);
  19208. this._startMonitoringGamepads();
  19209. };
  19210. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19211. if (!this.oneGamepadConnected) {
  19212. this.oneGamepadConnected = true;
  19213. if (Gamepads.gamepadDOMInfo) {
  19214. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19215. Gamepads.gamepadDOMInfo = null;
  19216. }
  19217. }
  19218. var newGamepad;
  19219. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19220. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19221. } else {
  19222. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19223. }
  19224. this.babylonGamepads.push(newGamepad);
  19225. return newGamepad;
  19226. };
  19227. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19228. for (var i in this.babylonGamepads) {
  19229. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19230. this.babylonGamepads.splice(i, 1);
  19231. break;
  19232. }
  19233. }
  19234. if (this.babylonGamepads.length == 0) {
  19235. this._stopMonitoringGamepads();
  19236. }
  19237. };
  19238. Gamepads.prototype._startMonitoringGamepads = function () {
  19239. if (!this.isMonitoring) {
  19240. this.isMonitoring = true;
  19241. this._checkGamepadsStatus();
  19242. }
  19243. };
  19244. Gamepads.prototype._stopMonitoringGamepads = function () {
  19245. this.isMonitoring = false;
  19246. };
  19247. Gamepads.prototype._checkGamepadsStatus = function () {
  19248. var _this = this;
  19249. this._updateGamepadObjects();
  19250. for (var i in this.babylonGamepads) {
  19251. this.babylonGamepads[i].update();
  19252. }
  19253. if (this.isMonitoring) {
  19254. if (window.requestAnimationFrame) {
  19255. window.requestAnimationFrame(function () {
  19256. _this._checkGamepadsStatus();
  19257. });
  19258. } else if (window.mozRequestAnimationFrame) {
  19259. window.mozRequestAnimationFrame(function () {
  19260. _this._checkGamepadsStatus();
  19261. });
  19262. } else if (window.webkitRequestAnimationFrame) {
  19263. window.webkitRequestAnimationFrame(function () {
  19264. _this._checkGamepadsStatus();
  19265. });
  19266. }
  19267. }
  19268. };
  19269. Gamepads.prototype._updateGamepadObjects = function () {
  19270. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19271. for (var i = 0; i < gamepads.length; i++) {
  19272. if (gamepads[i]) {
  19273. if (!(gamepads[i].index in this.babylonGamepads)) {
  19274. var newGamepad = this._addNewGamepad(gamepads[i]);
  19275. if (this._callbackGamepadConnected) {
  19276. this._callbackGamepadConnected(newGamepad);
  19277. }
  19278. } else {
  19279. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19280. }
  19281. }
  19282. }
  19283. };
  19284. return Gamepads;
  19285. })();
  19286. BABYLON.Gamepads = Gamepads;
  19287. var StickValues = (function () {
  19288. function StickValues(x, y) {
  19289. this.x = x;
  19290. this.y = y;
  19291. }
  19292. return StickValues;
  19293. })();
  19294. BABYLON.StickValues = StickValues;
  19295. var Gamepad = (function () {
  19296. function Gamepad(id, index, browserGamepad) {
  19297. this.id = id;
  19298. this.index = index;
  19299. this.browserGamepad = browserGamepad;
  19300. if (this.browserGamepad.axes.length >= 2) {
  19301. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19302. }
  19303. if (this.browserGamepad.axes.length >= 4) {
  19304. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19305. }
  19306. }
  19307. Gamepad.prototype.onleftstickchanged = function (callback) {
  19308. this._onleftstickchanged = callback;
  19309. };
  19310. Gamepad.prototype.onrightstickchanged = function (callback) {
  19311. this._onrightstickchanged = callback;
  19312. };
  19313. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19314. get: function () {
  19315. return this._leftStick;
  19316. },
  19317. set: function (newValues) {
  19318. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19319. this._onleftstickchanged(newValues);
  19320. }
  19321. this._leftStick = newValues;
  19322. },
  19323. enumerable: true,
  19324. configurable: true
  19325. });
  19326. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19327. get: function () {
  19328. return this._rightStick;
  19329. },
  19330. set: function (newValues) {
  19331. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19332. this._onrightstickchanged(newValues);
  19333. }
  19334. this._rightStick = newValues;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Gamepad.prototype.update = function () {
  19340. if (this._leftStick) {
  19341. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19342. }
  19343. if (this._rightStick) {
  19344. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19345. }
  19346. };
  19347. return Gamepad;
  19348. })();
  19349. BABYLON.Gamepad = Gamepad;
  19350. var GenericPad = (function (_super) {
  19351. __extends(GenericPad, _super);
  19352. function GenericPad(id, index, gamepad) {
  19353. _super.call(this, id, index, gamepad);
  19354. this.id = id;
  19355. this.index = index;
  19356. this.gamepad = gamepad;
  19357. this._buttons = new Array(gamepad.buttons.length);
  19358. }
  19359. GenericPad.prototype.onbuttondown = function (callback) {
  19360. this._onbuttondown = callback;
  19361. };
  19362. GenericPad.prototype.onbuttonup = function (callback) {
  19363. this._onbuttonup = callback;
  19364. };
  19365. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19366. if (newValue !== currentValue) {
  19367. if (this._onbuttondown && newValue === 1) {
  19368. this._onbuttondown(buttonIndex);
  19369. }
  19370. if (this._onbuttonup && newValue === 0) {
  19371. this._onbuttonup(buttonIndex);
  19372. }
  19373. }
  19374. return newValue;
  19375. };
  19376. GenericPad.prototype.update = function () {
  19377. _super.prototype.update.call(this);
  19378. for (var index = 0; index < this._buttons.length; index++) {
  19379. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19380. }
  19381. };
  19382. return GenericPad;
  19383. })(Gamepad);
  19384. BABYLON.GenericPad = GenericPad;
  19385. (function (Xbox360Button) {
  19386. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19387. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19388. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19389. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19390. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19391. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19392. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19393. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19394. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19395. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19396. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19397. var Xbox360Button = BABYLON.Xbox360Button;
  19398. (function (Xbox360Dpad) {
  19399. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19400. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19401. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19402. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19403. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19404. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19405. var Xbox360Pad = (function (_super) {
  19406. __extends(Xbox360Pad, _super);
  19407. function Xbox360Pad() {
  19408. _super.apply(this, arguments);
  19409. this._leftTrigger = 0;
  19410. this._rightTrigger = 0;
  19411. this._buttonA = 0;
  19412. this._buttonB = 0;
  19413. this._buttonX = 0;
  19414. this._buttonY = 0;
  19415. this._buttonBack = 0;
  19416. this._buttonStart = 0;
  19417. this._buttonLB = 0;
  19418. this._buttonRB = 0;
  19419. this._buttonLeftStick = 0;
  19420. this._buttonRightStick = 0;
  19421. this._dPadUp = 0;
  19422. this._dPadDown = 0;
  19423. this._dPadLeft = 0;
  19424. this._dPadRight = 0;
  19425. }
  19426. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19427. this._onlefttriggerchanged = callback;
  19428. };
  19429. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19430. this._onrighttriggerchanged = callback;
  19431. };
  19432. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19433. get: function () {
  19434. return this._leftTrigger;
  19435. },
  19436. set: function (newValue) {
  19437. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19438. this._onlefttriggerchanged(newValue);
  19439. }
  19440. this._leftTrigger = newValue;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19446. get: function () {
  19447. return this._rightTrigger;
  19448. },
  19449. set: function (newValue) {
  19450. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19451. this._onrighttriggerchanged(newValue);
  19452. }
  19453. this._rightTrigger = newValue;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19459. this._onbuttondown = callback;
  19460. };
  19461. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19462. this._onbuttonup = callback;
  19463. };
  19464. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19465. this._ondpaddown = callback;
  19466. };
  19467. Xbox360Pad.prototype.ondpadup = function (callback) {
  19468. this._ondpadup = callback;
  19469. };
  19470. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19471. if (newValue !== currentValue) {
  19472. if (this._onbuttondown && newValue === 1) {
  19473. this._onbuttondown(buttonType);
  19474. }
  19475. if (this._onbuttonup && newValue === 0) {
  19476. this._onbuttonup(buttonType);
  19477. }
  19478. }
  19479. return newValue;
  19480. };
  19481. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19482. if (newValue !== currentValue) {
  19483. if (this._ondpaddown && newValue === 1) {
  19484. this._ondpaddown(buttonType);
  19485. }
  19486. if (this._ondpadup && newValue === 0) {
  19487. this._ondpadup(buttonType);
  19488. }
  19489. }
  19490. return newValue;
  19491. };
  19492. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19493. get: function () {
  19494. return this._buttonA;
  19495. },
  19496. set: function (value) {
  19497. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19503. get: function () {
  19504. return this._buttonB;
  19505. },
  19506. set: function (value) {
  19507. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19513. get: function () {
  19514. return this._buttonX;
  19515. },
  19516. set: function (value) {
  19517. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19523. get: function () {
  19524. return this._buttonY;
  19525. },
  19526. set: function (value) {
  19527. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19533. get: function () {
  19534. return this._buttonStart;
  19535. },
  19536. set: function (value) {
  19537. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19543. get: function () {
  19544. return this._buttonBack;
  19545. },
  19546. set: function (value) {
  19547. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19553. get: function () {
  19554. return this._buttonLB;
  19555. },
  19556. set: function (value) {
  19557. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19563. get: function () {
  19564. return this._buttonRB;
  19565. },
  19566. set: function (value) {
  19567. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19573. get: function () {
  19574. return this._buttonLeftStick;
  19575. },
  19576. set: function (value) {
  19577. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19583. get: function () {
  19584. return this._buttonRightStick;
  19585. },
  19586. set: function (value) {
  19587. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19588. },
  19589. enumerable: true,
  19590. configurable: true
  19591. });
  19592. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19593. get: function () {
  19594. return this._dPadUp;
  19595. },
  19596. set: function (value) {
  19597. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19603. get: function () {
  19604. return this._dPadDown;
  19605. },
  19606. set: function (value) {
  19607. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19613. get: function () {
  19614. return this._dPadLeft;
  19615. },
  19616. set: function (value) {
  19617. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19623. get: function () {
  19624. return this._dPadRight;
  19625. },
  19626. set: function (value) {
  19627. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Xbox360Pad.prototype.update = function () {
  19633. _super.prototype.update.call(this);
  19634. this.buttonA = this.browserGamepad.buttons[0].value;
  19635. this.buttonB = this.browserGamepad.buttons[1].value;
  19636. this.buttonX = this.browserGamepad.buttons[2].value;
  19637. this.buttonY = this.browserGamepad.buttons[3].value;
  19638. this.buttonLB = this.browserGamepad.buttons[4].value;
  19639. this.buttonRB = this.browserGamepad.buttons[5].value;
  19640. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19641. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19642. this.buttonBack = this.browserGamepad.buttons[8].value;
  19643. this.buttonStart = this.browserGamepad.buttons[9].value;
  19644. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19645. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19646. this.dPadUp = this.browserGamepad.buttons[12].value;
  19647. this.dPadDown = this.browserGamepad.buttons[13].value;
  19648. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19649. this.dPadRight = this.browserGamepad.buttons[15].value;
  19650. };
  19651. return Xbox360Pad;
  19652. })(Gamepad);
  19653. BABYLON.Xbox360Pad = Xbox360Pad;
  19654. })(BABYLON || (BABYLON = {}));
  19655. var __extends = this.__extends || function (d, b) {
  19656. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19657. function __() { this.constructor = d; }
  19658. __.prototype = b.prototype;
  19659. d.prototype = new __();
  19660. };
  19661. var BABYLON;
  19662. (function (BABYLON) {
  19663. var GamepadCamera = (function (_super) {
  19664. __extends(GamepadCamera, _super);
  19665. function GamepadCamera(name, position, scene) {
  19666. var _this = this;
  19667. _super.call(this, name, position, scene);
  19668. this.angularSensibility = 200;
  19669. this.moveSensibility = 75;
  19670. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19671. _this._onNewGameConnected(gamepad);
  19672. });
  19673. }
  19674. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19675. if (gamepad.index === 0) {
  19676. this._gamepad = gamepad;
  19677. }
  19678. };
  19679. GamepadCamera.prototype._checkInputs = function () {
  19680. if (!this._gamepad) {
  19681. return;
  19682. }
  19683. var LSValues = this._gamepad.leftStick;
  19684. var normalizedLX = LSValues.x / this.moveSensibility;
  19685. var normalizedLY = LSValues.y / this.moveSensibility;
  19686. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19687. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19688. var RSValues = this._gamepad.rightStick;
  19689. var normalizedRX = RSValues.x / this.angularSensibility;
  19690. var normalizedRY = RSValues.y / this.angularSensibility;
  19691. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19692. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19693. ;
  19694. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19695. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19696. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19697. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19698. };
  19699. GamepadCamera.prototype.dispose = function () {
  19700. this._gamepads.dispose();
  19701. _super.prototype.dispose.call(this);
  19702. };
  19703. return GamepadCamera;
  19704. })(BABYLON.FreeCamera);
  19705. BABYLON.GamepadCamera = GamepadCamera;
  19706. })(BABYLON || (BABYLON = {}));
  19707. var __extends = this.__extends || function (d, b) {
  19708. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19709. function __() { this.constructor = d; }
  19710. __.prototype = b.prototype;
  19711. d.prototype = new __();
  19712. };
  19713. var BABYLON;
  19714. (function (BABYLON) {
  19715. var LinesMesh = (function (_super) {
  19716. __extends(LinesMesh, _super);
  19717. function LinesMesh(name, scene, updatable) {
  19718. if (typeof updatable === "undefined") { updatable = false; }
  19719. _super.call(this, name, scene);
  19720. this.color = new BABYLON.Color3(1, 1, 1);
  19721. this.alpha = 1;
  19722. this._indices = new Array();
  19723. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19724. attributes: ["position"],
  19725. uniforms: ["worldViewProjection", "color"],
  19726. needAlphaBlending: true
  19727. });
  19728. }
  19729. Object.defineProperty(LinesMesh.prototype, "material", {
  19730. get: function () {
  19731. return this._colorShader;
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19737. get: function () {
  19738. return false;
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19744. get: function () {
  19745. return false;
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19751. var engine = this.getScene().getEngine();
  19752. var indexToBind = this._geometry.getIndexBuffer();
  19753. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19754. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19755. };
  19756. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19757. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19758. return;
  19759. }
  19760. var engine = this.getScene().getEngine();
  19761. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19762. };
  19763. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19764. return null;
  19765. };
  19766. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19767. this._colorShader.dispose();
  19768. _super.prototype.dispose.call(this, doNotRecurse);
  19769. };
  19770. return LinesMesh;
  19771. })(BABYLON.Mesh);
  19772. BABYLON.LinesMesh = LinesMesh;
  19773. })(BABYLON || (BABYLON = {}));
  19774. var BABYLON;
  19775. (function (BABYLON) {
  19776. var OutlineRenderer = (function () {
  19777. function OutlineRenderer(scene) {
  19778. this._scene = scene;
  19779. }
  19780. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19781. var scene = this._scene;
  19782. var engine = this._scene.getEngine();
  19783. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19784. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19785. return;
  19786. }
  19787. var mesh = subMesh.getRenderingMesh();
  19788. var material = subMesh.getMaterial();
  19789. engine.enableEffect(this._effect);
  19790. this._effect.setFloat("offset", mesh.outlineWidth);
  19791. this._effect.setColor3("color", mesh.outlineColor);
  19792. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19793. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19794. if (useBones) {
  19795. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19796. }
  19797. mesh._bind(subMesh, this._effect, false);
  19798. if (material && material.needAlphaTesting()) {
  19799. var alphaTexture = material.getAlphaTestTexture();
  19800. this._effect.setTexture("diffuseSampler", alphaTexture);
  19801. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19802. }
  19803. if (hardwareInstancedRendering) {
  19804. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19805. } else {
  19806. if (batch.renderSelf[subMesh._id]) {
  19807. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19808. mesh._draw(subMesh, true);
  19809. }
  19810. if (batch.visibleInstances[subMesh._id]) {
  19811. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19812. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19813. this._effect.setMatrix("world", instance.getWorldMatrix());
  19814. mesh._draw(subMesh, true);
  19815. }
  19816. }
  19817. }
  19818. };
  19819. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19820. var defines = [];
  19821. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19822. var mesh = subMesh.getMesh();
  19823. var material = subMesh.getMaterial();
  19824. if (material && material.needAlphaTesting()) {
  19825. defines.push("#define ALPHATEST");
  19826. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19827. attribs.push(BABYLON.VertexBuffer.UVKind);
  19828. defines.push("#define UV1");
  19829. }
  19830. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19831. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19832. defines.push("#define UV2");
  19833. }
  19834. }
  19835. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19836. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19837. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19838. defines.push("#define BONES");
  19839. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19840. }
  19841. if (useInstances) {
  19842. defines.push("#define INSTANCES");
  19843. attribs.push("world0");
  19844. attribs.push("world1");
  19845. attribs.push("world2");
  19846. attribs.push("world3");
  19847. }
  19848. var join = defines.join("\n");
  19849. if (this._cachedDefines != join) {
  19850. this._cachedDefines = join;
  19851. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19852. }
  19853. return this._effect.isReady();
  19854. };
  19855. return OutlineRenderer;
  19856. })();
  19857. BABYLON.OutlineRenderer = OutlineRenderer;
  19858. })(BABYLON || (BABYLON = {}));
  19859. var BABYLON;
  19860. (function (BABYLON) {
  19861. var MeshAssetTask = (function () {
  19862. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19863. this.name = name;
  19864. this.meshesNames = meshesNames;
  19865. this.rootUrl = rootUrl;
  19866. this.sceneFilename = sceneFilename;
  19867. this.isCompleted = false;
  19868. }
  19869. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19870. var _this = this;
  19871. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19872. _this.loadedMeshes = meshes;
  19873. _this.loadedParticleSystems = particleSystems;
  19874. _this.loadedSkeletons = skeletons;
  19875. _this.isCompleted = true;
  19876. if (_this.onSuccess) {
  19877. _this.onSuccess(_this);
  19878. }
  19879. onSuccess();
  19880. }, null, function () {
  19881. if (_this.onError) {
  19882. _this.onError(_this);
  19883. }
  19884. onError();
  19885. });
  19886. };
  19887. return MeshAssetTask;
  19888. })();
  19889. BABYLON.MeshAssetTask = MeshAssetTask;
  19890. var TextFileAssetTask = (function () {
  19891. function TextFileAssetTask(name, url) {
  19892. this.name = name;
  19893. this.url = url;
  19894. this.isCompleted = false;
  19895. }
  19896. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19897. var _this = this;
  19898. BABYLON.Tools.LoadFile(this.url, function (data) {
  19899. _this.text = data;
  19900. _this.isCompleted = true;
  19901. if (_this.onSuccess) {
  19902. _this.onSuccess(_this);
  19903. }
  19904. onSuccess();
  19905. }, null, scene.database, false, function () {
  19906. if (_this.onError) {
  19907. _this.onError(_this);
  19908. }
  19909. onError();
  19910. });
  19911. };
  19912. return TextFileAssetTask;
  19913. })();
  19914. BABYLON.TextFileAssetTask = TextFileAssetTask;
  19915. var BinaryFileAssetTask = (function () {
  19916. function BinaryFileAssetTask(name, url) {
  19917. this.name = name;
  19918. this.url = url;
  19919. this.isCompleted = false;
  19920. }
  19921. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19922. var _this = this;
  19923. BABYLON.Tools.LoadFile(this.url, function (data) {
  19924. _this.data = data;
  19925. _this.isCompleted = true;
  19926. if (_this.onSuccess) {
  19927. _this.onSuccess(_this);
  19928. }
  19929. onSuccess();
  19930. }, null, scene.database, true, function () {
  19931. if (_this.onError) {
  19932. _this.onError(_this);
  19933. }
  19934. onError();
  19935. });
  19936. };
  19937. return BinaryFileAssetTask;
  19938. })();
  19939. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  19940. var ImageAssetTask = (function () {
  19941. function ImageAssetTask(name, url) {
  19942. this.name = name;
  19943. this.url = url;
  19944. this.isCompleted = false;
  19945. }
  19946. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19947. var _this = this;
  19948. var img = new Image();
  19949. img.onload = function () {
  19950. _this.image = img;
  19951. _this.isCompleted = true;
  19952. if (_this.onSuccess) {
  19953. _this.onSuccess(_this);
  19954. }
  19955. onSuccess();
  19956. };
  19957. img.onerror = function () {
  19958. if (_this.onError) {
  19959. _this.onError(_this);
  19960. }
  19961. onError();
  19962. };
  19963. };
  19964. return ImageAssetTask;
  19965. })();
  19966. BABYLON.ImageAssetTask = ImageAssetTask;
  19967. var AssetsManager = (function () {
  19968. function AssetsManager(scene) {
  19969. this._tasks = new Array();
  19970. this._waitingTasksCount = 0;
  19971. this.useDefaultLoadingScreen = true;
  19972. this._scene = scene;
  19973. }
  19974. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  19975. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  19976. this._tasks.push(task);
  19977. return task;
  19978. };
  19979. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  19980. var task = new TextFileAssetTask(taskName, url);
  19981. this._tasks.push(task);
  19982. return task;
  19983. };
  19984. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  19985. var task = new BinaryFileAssetTask(taskName, url);
  19986. this._tasks.push(task);
  19987. return task;
  19988. };
  19989. AssetsManager.prototype.addImageTask = function (taskName, url) {
  19990. var task = new ImageAssetTask(taskName, url);
  19991. this._tasks.push(task);
  19992. return task;
  19993. };
  19994. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  19995. this._waitingTasksCount--;
  19996. if (this._waitingTasksCount === 0) {
  19997. if (this.onFinish) {
  19998. this.onFinish(this._tasks);
  19999. }
  20000. this._scene.getEngine().hideLoadingUI();
  20001. }
  20002. };
  20003. AssetsManager.prototype._runTask = function (task) {
  20004. var _this = this;
  20005. task.run(this._scene, function () {
  20006. if (_this.onTaskSuccess) {
  20007. _this.onTaskSuccess(task);
  20008. }
  20009. _this._decreaseWaitingTasksCount();
  20010. }, function () {
  20011. if (_this.onTaskError) {
  20012. _this.onTaskError(task);
  20013. }
  20014. _this._decreaseWaitingTasksCount();
  20015. });
  20016. };
  20017. AssetsManager.prototype.reset = function () {
  20018. this._tasks = new Array();
  20019. return this;
  20020. };
  20021. AssetsManager.prototype.load = function () {
  20022. this._waitingTasksCount = this._tasks.length;
  20023. if (this._waitingTasksCount === 0) {
  20024. if (this.onFinish) {
  20025. this.onFinish(this._tasks);
  20026. }
  20027. return this;
  20028. }
  20029. if (this.useDefaultLoadingScreen) {
  20030. this._scene.getEngine().displayLoadingUI();
  20031. }
  20032. for (var index = 0; index < this._tasks.length; index++) {
  20033. var task = this._tasks[index];
  20034. this._runTask(task);
  20035. }
  20036. return this;
  20037. };
  20038. return AssetsManager;
  20039. })();
  20040. BABYLON.AssetsManager = AssetsManager;
  20041. })(BABYLON || (BABYLON = {}));