babylon.2.2.max.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = 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);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var u = Vector3.Normalize(axis1);
  845. var w = Vector3.Normalize(axis3);
  846. // world axis
  847. var X = Axis.X;
  848. var Y = Axis.Y;
  849. // equation unknowns and vars
  850. var yaw = 0.0;
  851. var pitch = 0.0;
  852. var roll = 0.0;
  853. var x = 0.0;
  854. var y = 0.0;
  855. var z = 0.0;
  856. var t = 0.0;
  857. var sign = -1.0;
  858. var nbRevert = 0;
  859. var cross;
  860. var dot = 0.0;
  861. // step 1 : rotation around w
  862. // Rv3(u) = u1, and u1 belongs to plane xOz
  863. // Rv3(w) = w1 = w invariant
  864. var u1;
  865. var v1;
  866. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  867. z = 1.0;
  868. }
  869. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  870. x = 1.0;
  871. }
  872. else {
  873. t = w.z / w.x;
  874. x = -t * Math.sqrt(1 / (1 + t * t));
  875. z = Math.sqrt(1 / (1 + t * t));
  876. }
  877. u1 = new Vector3(x, y, z);
  878. u1.normalize();
  879. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  880. v1.normalize();
  881. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  882. cross.normalize();
  883. if (Vector3.Dot(w, cross) < 0) {
  884. sign = 1.0;
  885. }
  886. dot = Vector3.Dot(u, u1);
  887. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  888. roll = Math.acos(dot) * sign;
  889. if (Vector3.Dot(u1, X) < 0) {
  890. roll = Math.PI + roll;
  891. u1 = u1.scaleInPlace(-1);
  892. v1 = v1.scaleInPlace(-1);
  893. nbRevert++;
  894. }
  895. // step 2 : rotate around u1
  896. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  897. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  898. var w2;
  899. var v2;
  900. x = 0.0;
  901. y = 0.0;
  902. z = 0.0;
  903. sign = -1;
  904. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  905. x = 1.0;
  906. }
  907. else {
  908. t = u1.z / u1.x;
  909. x = -t * Math.sqrt(1 / (1 + t * t));
  910. z = Math.sqrt(1 / (1 + t * t));
  911. }
  912. w2 = new Vector3(x, y, z);
  913. w2.normalize();
  914. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  915. v2.normalize();
  916. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  917. cross.normalize();
  918. if (Vector3.Dot(u1, cross) < 0) {
  919. sign = 1.0;
  920. }
  921. dot = Vector3.Dot(w, w2);
  922. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  923. pitch = Math.acos(dot) * sign;
  924. if (Vector3.Dot(v2, Y) < 0) {
  925. pitch = Math.PI + pitch;
  926. v2 = v2.scaleInPlace(-1);
  927. w2 = w2.scaleInPlace(-1);
  928. nbRevert++;
  929. }
  930. // step 3 : rotate around v2
  931. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  932. sign = -1;
  933. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  934. cross.normalize();
  935. if (Vector3.Dot(cross, Y) < 0) {
  936. sign = 1.0;
  937. }
  938. dot = Vector3.Dot(u1, X);
  939. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  940. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  941. if (dot < 0 && nbRevert < 2) {
  942. yaw = Math.PI + yaw;
  943. }
  944. return new Vector3(pitch, yaw, roll);
  945. };
  946. return Vector3;
  947. })();
  948. BABYLON.Vector3 = Vector3;
  949. //Vector4 class created for EulerAngle class conversion to Quaternion
  950. var Vector4 = (function () {
  951. function Vector4(x, y, z, w) {
  952. this.x = x;
  953. this.y = y;
  954. this.z = z;
  955. this.w = w;
  956. }
  957. Vector4.prototype.toString = function () {
  958. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  959. };
  960. // Operators
  961. Vector4.prototype.asArray = function () {
  962. var result = [];
  963. this.toArray(result, 0);
  964. return result;
  965. };
  966. Vector4.prototype.toArray = function (array, index) {
  967. if (index === undefined) {
  968. index = 0;
  969. }
  970. array[index] = this.x;
  971. array[index + 1] = this.y;
  972. array[index + 2] = this.z;
  973. array[index + 3] = this.w;
  974. return this;
  975. };
  976. Vector4.prototype.addInPlace = function (otherVector) {
  977. this.x += otherVector.x;
  978. this.y += otherVector.y;
  979. this.z += otherVector.z;
  980. this.w += otherVector.w;
  981. return this;
  982. };
  983. Vector4.prototype.add = function (otherVector) {
  984. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  985. };
  986. Vector4.prototype.addToRef = function (otherVector, result) {
  987. result.x = this.x + otherVector.x;
  988. result.y = this.y + otherVector.y;
  989. result.z = this.z + otherVector.z;
  990. result.w = this.w + otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.subtractInPlace = function (otherVector) {
  994. this.x -= otherVector.x;
  995. this.y -= otherVector.y;
  996. this.z -= otherVector.z;
  997. this.w -= otherVector.w;
  998. return this;
  999. };
  1000. Vector4.prototype.subtract = function (otherVector) {
  1001. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1002. };
  1003. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1004. result.x = this.x - otherVector.x;
  1005. result.y = this.y - otherVector.y;
  1006. result.z = this.z - otherVector.z;
  1007. result.w = this.w - otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1011. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1012. };
  1013. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1014. result.x = this.x - x;
  1015. result.y = this.y - y;
  1016. result.z = this.z - z;
  1017. result.w = this.w - w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.negate = function () {
  1021. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1022. };
  1023. Vector4.prototype.scaleInPlace = function (scale) {
  1024. this.x *= scale;
  1025. this.y *= scale;
  1026. this.z *= scale;
  1027. this.w *= scale;
  1028. return this;
  1029. };
  1030. Vector4.prototype.scale = function (scale) {
  1031. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1032. };
  1033. Vector4.prototype.scaleToRef = function (scale, result) {
  1034. result.x = this.x * scale;
  1035. result.y = this.y * scale;
  1036. result.z = this.z * scale;
  1037. result.w = this.w * scale;
  1038. };
  1039. Vector4.prototype.equals = function (otherVector) {
  1040. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1041. };
  1042. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1043. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1044. return otherVector
  1045. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1046. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1047. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1048. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1049. };
  1050. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1051. return this.x === x && this.y === y && this.z === z && this.w === w;
  1052. };
  1053. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1054. this.x *= otherVector.x;
  1055. this.y *= otherVector.y;
  1056. this.z *= otherVector.z;
  1057. this.w *= otherVector.w;
  1058. return this;
  1059. };
  1060. Vector4.prototype.multiply = function (otherVector) {
  1061. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1062. };
  1063. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1064. result.x = this.x * otherVector.x;
  1065. result.y = this.y * otherVector.y;
  1066. result.z = this.z * otherVector.z;
  1067. result.w = this.w * otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1071. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1072. };
  1073. Vector4.prototype.divide = function (otherVector) {
  1074. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1075. };
  1076. Vector4.prototype.divideToRef = function (otherVector, result) {
  1077. result.x = this.x / otherVector.x;
  1078. result.y = this.y / otherVector.y;
  1079. result.z = this.z / otherVector.z;
  1080. result.w = this.w / otherVector.w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.MinimizeInPlace = function (other) {
  1084. if (other.x < this.x)
  1085. this.x = other.x;
  1086. if (other.y < this.y)
  1087. this.y = other.y;
  1088. if (other.z < this.z)
  1089. this.z = other.z;
  1090. if (other.w < this.w)
  1091. this.w = other.w;
  1092. return this;
  1093. };
  1094. Vector4.prototype.MaximizeInPlace = function (other) {
  1095. if (other.x > this.x)
  1096. this.x = other.x;
  1097. if (other.y > this.y)
  1098. this.y = other.y;
  1099. if (other.z > this.z)
  1100. this.z = other.z;
  1101. if (other.w > this.w)
  1102. this.w = other.w;
  1103. return this;
  1104. };
  1105. // Properties
  1106. Vector4.prototype.length = function () {
  1107. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1108. };
  1109. Vector4.prototype.lengthSquared = function () {
  1110. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1111. };
  1112. // Methods
  1113. Vector4.prototype.normalize = function () {
  1114. var len = this.length();
  1115. if (len === 0)
  1116. return this;
  1117. var num = 1.0 / len;
  1118. this.x *= num;
  1119. this.y *= num;
  1120. this.z *= num;
  1121. this.w *= num;
  1122. return this;
  1123. };
  1124. Vector4.prototype.clone = function () {
  1125. return new Vector4(this.x, this.y, this.z, this.w);
  1126. };
  1127. Vector4.prototype.copyFrom = function (source) {
  1128. this.x = source.x;
  1129. this.y = source.y;
  1130. this.z = source.z;
  1131. this.w = source.w;
  1132. return this;
  1133. };
  1134. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1135. this.x = x;
  1136. this.y = y;
  1137. this.z = z;
  1138. this.w = w;
  1139. return this;
  1140. };
  1141. // Statics
  1142. Vector4.FromArray = function (array, offset) {
  1143. if (!offset) {
  1144. offset = 0;
  1145. }
  1146. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1147. };
  1148. Vector4.FromArrayToRef = function (array, offset, result) {
  1149. result.x = array[offset];
  1150. result.y = array[offset + 1];
  1151. result.z = array[offset + 2];
  1152. result.w = array[offset + 3];
  1153. };
  1154. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1155. result.x = array[offset];
  1156. result.y = array[offset + 1];
  1157. result.z = array[offset + 2];
  1158. result.w = array[offset + 3];
  1159. };
  1160. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1161. result.x = x;
  1162. result.y = y;
  1163. result.z = z;
  1164. result.w = w;
  1165. };
  1166. Vector4.Zero = function () {
  1167. return new Vector4(0, 0, 0, 0);
  1168. };
  1169. Vector4.Normalize = function (vector) {
  1170. var result = Vector4.Zero();
  1171. Vector4.NormalizeToRef(vector, result);
  1172. return result;
  1173. };
  1174. Vector4.NormalizeToRef = function (vector, result) {
  1175. result.copyFrom(vector);
  1176. result.normalize();
  1177. };
  1178. Vector4.Minimize = function (left, right) {
  1179. var min = left.clone();
  1180. min.MinimizeInPlace(right);
  1181. return min;
  1182. };
  1183. Vector4.Maximize = function (left, right) {
  1184. var max = left.clone();
  1185. max.MaximizeInPlace(right);
  1186. return max;
  1187. };
  1188. Vector4.Distance = function (value1, value2) {
  1189. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1190. };
  1191. Vector4.DistanceSquared = function (value1, value2) {
  1192. var x = value1.x - value2.x;
  1193. var y = value1.y - value2.y;
  1194. var z = value1.z - value2.z;
  1195. var w = value1.w - value2.w;
  1196. return (x * x) + (y * y) + (z * z) + (w * w);
  1197. };
  1198. Vector4.Center = function (value1, value2) {
  1199. var center = value1.add(value2);
  1200. center.scaleInPlace(0.5);
  1201. return center;
  1202. };
  1203. return Vector4;
  1204. })();
  1205. BABYLON.Vector4 = Vector4;
  1206. var Quaternion = (function () {
  1207. function Quaternion(x, y, z, w) {
  1208. if (x === void 0) { x = 0; }
  1209. if (y === void 0) { y = 0; }
  1210. if (z === void 0) { z = 0; }
  1211. if (w === void 0) { w = 1; }
  1212. this.x = x;
  1213. this.y = y;
  1214. this.z = z;
  1215. this.w = w;
  1216. }
  1217. Quaternion.prototype.toString = function () {
  1218. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1219. };
  1220. Quaternion.prototype.asArray = function () {
  1221. return [this.x, this.y, this.z, this.w];
  1222. };
  1223. Quaternion.prototype.equals = function (otherQuaternion) {
  1224. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1225. };
  1226. Quaternion.prototype.clone = function () {
  1227. return new Quaternion(this.x, this.y, this.z, this.w);
  1228. };
  1229. Quaternion.prototype.copyFrom = function (other) {
  1230. this.x = other.x;
  1231. this.y = other.y;
  1232. this.z = other.z;
  1233. this.w = other.w;
  1234. return this;
  1235. };
  1236. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. return this;
  1242. };
  1243. Quaternion.prototype.add = function (other) {
  1244. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1245. };
  1246. Quaternion.prototype.subtract = function (other) {
  1247. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1248. };
  1249. Quaternion.prototype.scale = function (value) {
  1250. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1251. };
  1252. Quaternion.prototype.multiply = function (q1) {
  1253. var result = new Quaternion(0, 0, 0, 1.0);
  1254. this.multiplyToRef(q1, result);
  1255. return result;
  1256. };
  1257. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1258. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1259. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1260. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1261. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1262. result.copyFromFloats(x, y, z, w);
  1263. return this;
  1264. };
  1265. Quaternion.prototype.length = function () {
  1266. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1267. };
  1268. Quaternion.prototype.normalize = function () {
  1269. var length = 1.0 / this.length();
  1270. this.x *= length;
  1271. this.y *= length;
  1272. this.z *= length;
  1273. this.w *= length;
  1274. return this;
  1275. };
  1276. Quaternion.prototype.toEulerAngles = function () {
  1277. var result = Vector3.Zero();
  1278. this.toEulerAnglesToRef(result);
  1279. return result;
  1280. };
  1281. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1282. //result is an EulerAngles in the in the z-x-z convention
  1283. var qx = this.x;
  1284. var qy = this.y;
  1285. var qz = this.z;
  1286. var qw = this.w;
  1287. var qxy = qx * qy;
  1288. var qxz = qx * qz;
  1289. var qwy = qw * qy;
  1290. var qwz = qw * qz;
  1291. var qwx = qw * qx;
  1292. var qyz = qy * qz;
  1293. var sqx = qx * qx;
  1294. var sqy = qy * qy;
  1295. var determinant = sqx + sqy;
  1296. if (determinant !== 0.000 && determinant !== 1.000) {
  1297. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1298. result.y = Math.acos(1 - 2 * determinant);
  1299. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1300. }
  1301. else {
  1302. if (determinant === 0.0) {
  1303. result.x = 0.0;
  1304. result.y = 0.0;
  1305. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1306. }
  1307. else {
  1308. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1309. result.y = Math.PI;
  1310. result.z = 0.0;
  1311. }
  1312. }
  1313. return this;
  1314. };
  1315. Quaternion.prototype.toRotationMatrix = function (result) {
  1316. var xx = this.x * this.x;
  1317. var yy = this.y * this.y;
  1318. var zz = this.z * this.z;
  1319. var xy = this.x * this.y;
  1320. var zw = this.z * this.w;
  1321. var zx = this.z * this.x;
  1322. var yw = this.y * this.w;
  1323. var yz = this.y * this.z;
  1324. var xw = this.x * this.w;
  1325. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1326. result.m[1] = 2.0 * (xy + zw);
  1327. result.m[2] = 2.0 * (zx - yw);
  1328. result.m[3] = 0;
  1329. result.m[4] = 2.0 * (xy - zw);
  1330. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1331. result.m[6] = 2.0 * (yz + xw);
  1332. result.m[7] = 0;
  1333. result.m[8] = 2.0 * (zx + yw);
  1334. result.m[9] = 2.0 * (yz - xw);
  1335. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1336. result.m[11] = 0;
  1337. result.m[12] = 0;
  1338. result.m[13] = 0;
  1339. result.m[14] = 0;
  1340. result.m[15] = 1.0;
  1341. return this;
  1342. };
  1343. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1344. Quaternion.FromRotationMatrixToRef(matrix, this);
  1345. return this;
  1346. };
  1347. // Statics
  1348. Quaternion.FromRotationMatrix = function (matrix) {
  1349. var result = new Quaternion();
  1350. Quaternion.FromRotationMatrixToRef(matrix, result);
  1351. return result;
  1352. };
  1353. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1354. var data = matrix.m;
  1355. var m11 = data[0], m12 = data[4], m13 = data[8];
  1356. var m21 = data[1], m22 = data[5], m23 = data[9];
  1357. var m31 = data[2], m32 = data[6], m33 = data[10];
  1358. var trace = m11 + m22 + m33;
  1359. var s;
  1360. if (trace > 0) {
  1361. s = 0.5 / Math.sqrt(trace + 1.0);
  1362. result.w = 0.25 / s;
  1363. result.x = (m32 - m23) * s;
  1364. result.y = (m13 - m31) * s;
  1365. result.z = (m21 - m12) * s;
  1366. }
  1367. else if (m11 > m22 && m11 > m33) {
  1368. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1369. result.w = (m32 - m23) / s;
  1370. result.x = 0.25 * s;
  1371. result.y = (m12 + m21) / s;
  1372. result.z = (m13 + m31) / s;
  1373. }
  1374. else if (m22 > m33) {
  1375. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1376. result.w = (m13 - m31) / s;
  1377. result.x = (m12 + m21) / s;
  1378. result.y = 0.25 * s;
  1379. result.z = (m23 + m32) / s;
  1380. }
  1381. else {
  1382. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1383. result.w = (m21 - m12) / s;
  1384. result.x = (m13 + m31) / s;
  1385. result.y = (m23 + m32) / s;
  1386. result.z = 0.25 * s;
  1387. }
  1388. };
  1389. Quaternion.Inverse = function (q) {
  1390. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1391. };
  1392. Quaternion.Identity = function () {
  1393. return new Quaternion(0, 0, 0, 1);
  1394. };
  1395. Quaternion.RotationAxis = function (axis, angle) {
  1396. var result = new Quaternion();
  1397. var sin = Math.sin(angle / 2);
  1398. result.w = Math.cos(angle / 2);
  1399. result.x = axis.x * sin;
  1400. result.y = axis.y * sin;
  1401. result.z = axis.z * sin;
  1402. return result;
  1403. };
  1404. Quaternion.FromArray = function (array, offset) {
  1405. if (!offset) {
  1406. offset = 0;
  1407. }
  1408. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1409. };
  1410. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1411. var result = new Quaternion();
  1412. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1413. return result;
  1414. };
  1415. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1416. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1417. var halfRoll = roll * 0.5;
  1418. var halfPitch = pitch * 0.5;
  1419. var halfYaw = yaw * 0.5;
  1420. var sinRoll = Math.sin(halfRoll);
  1421. var cosRoll = Math.cos(halfRoll);
  1422. var sinPitch = Math.sin(halfPitch);
  1423. var cosPitch = Math.cos(halfPitch);
  1424. var sinYaw = Math.sin(halfYaw);
  1425. var cosYaw = Math.cos(halfYaw);
  1426. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1427. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1428. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1429. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1430. };
  1431. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1432. var result = new Quaternion();
  1433. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1434. return result;
  1435. };
  1436. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1437. // Produces a quaternion from Euler angles in the z-x-z orientation
  1438. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1439. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1440. var halfBeta = beta * 0.5;
  1441. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1442. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1443. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1444. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1445. };
  1446. Quaternion.Slerp = function (left, right, amount) {
  1447. var num2;
  1448. var num3;
  1449. var num = amount;
  1450. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1451. var flag = false;
  1452. if (num4 < 0) {
  1453. flag = true;
  1454. num4 = -num4;
  1455. }
  1456. if (num4 > 0.999999) {
  1457. num3 = 1 - num;
  1458. num2 = flag ? -num : num;
  1459. }
  1460. else {
  1461. var num5 = Math.acos(num4);
  1462. var num6 = (1.0 / Math.sin(num5));
  1463. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1464. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1465. }
  1466. 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));
  1467. };
  1468. return Quaternion;
  1469. })();
  1470. BABYLON.Quaternion = Quaternion;
  1471. var Matrix = (function () {
  1472. function Matrix() {
  1473. this.m = new Float32Array(16);
  1474. }
  1475. // Properties
  1476. Matrix.prototype.isIdentity = function () {
  1477. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1478. return false;
  1479. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1480. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1481. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1482. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1483. return false;
  1484. return true;
  1485. };
  1486. Matrix.prototype.determinant = function () {
  1487. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1488. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1489. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1490. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1491. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1492. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1493. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1494. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1495. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1496. };
  1497. // Methods
  1498. Matrix.prototype.toArray = function () {
  1499. return this.m;
  1500. };
  1501. Matrix.prototype.asArray = function () {
  1502. return this.toArray();
  1503. };
  1504. Matrix.prototype.invert = function () {
  1505. this.invertToRef(this);
  1506. return this;
  1507. };
  1508. Matrix.prototype.reset = function () {
  1509. for (var index = 0; index < 16; index++) {
  1510. this.m[index] = 0;
  1511. }
  1512. return this;
  1513. };
  1514. Matrix.prototype.add = function (other) {
  1515. var result = new Matrix();
  1516. this.addToRef(other, result);
  1517. return result;
  1518. };
  1519. Matrix.prototype.addToRef = function (other, result) {
  1520. for (var index = 0; index < 16; index++) {
  1521. result.m[index] = this.m[index] + other.m[index];
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.addToSelf = function (other) {
  1526. for (var index = 0; index < 16; index++) {
  1527. this.m[index] += other.m[index];
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.invertToRef = function (other) {
  1532. var l1 = this.m[0];
  1533. var l2 = this.m[1];
  1534. var l3 = this.m[2];
  1535. var l4 = this.m[3];
  1536. var l5 = this.m[4];
  1537. var l6 = this.m[5];
  1538. var l7 = this.m[6];
  1539. var l8 = this.m[7];
  1540. var l9 = this.m[8];
  1541. var l10 = this.m[9];
  1542. var l11 = this.m[10];
  1543. var l12 = this.m[11];
  1544. var l13 = this.m[12];
  1545. var l14 = this.m[13];
  1546. var l15 = this.m[14];
  1547. var l16 = this.m[15];
  1548. var l17 = (l11 * l16) - (l12 * l15);
  1549. var l18 = (l10 * l16) - (l12 * l14);
  1550. var l19 = (l10 * l15) - (l11 * l14);
  1551. var l20 = (l9 * l16) - (l12 * l13);
  1552. var l21 = (l9 * l15) - (l11 * l13);
  1553. var l22 = (l9 * l14) - (l10 * l13);
  1554. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1555. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1556. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1557. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1558. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1559. var l28 = (l7 * l16) - (l8 * l15);
  1560. var l29 = (l6 * l16) - (l8 * l14);
  1561. var l30 = (l6 * l15) - (l7 * l14);
  1562. var l31 = (l5 * l16) - (l8 * l13);
  1563. var l32 = (l5 * l15) - (l7 * l13);
  1564. var l33 = (l5 * l14) - (l6 * l13);
  1565. var l34 = (l7 * l12) - (l8 * l11);
  1566. var l35 = (l6 * l12) - (l8 * l10);
  1567. var l36 = (l6 * l11) - (l7 * l10);
  1568. var l37 = (l5 * l12) - (l8 * l9);
  1569. var l38 = (l5 * l11) - (l7 * l9);
  1570. var l39 = (l5 * l10) - (l6 * l9);
  1571. other.m[0] = l23 * l27;
  1572. other.m[4] = l24 * l27;
  1573. other.m[8] = l25 * l27;
  1574. other.m[12] = l26 * l27;
  1575. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1576. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1577. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1578. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1579. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1580. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1581. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1582. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1583. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1584. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1585. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1586. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1587. return this;
  1588. };
  1589. Matrix.prototype.invertToRefSIMD = function (other) {
  1590. var src = this.m;
  1591. var dest = other.m;
  1592. var row0, row1, row2, row3;
  1593. var tmp1;
  1594. var minor0, minor1, minor2, minor3;
  1595. var det;
  1596. // Load the 4 rows
  1597. var src0 = SIMD.float32x4.load(src, 0);
  1598. var src1 = SIMD.float32x4.load(src, 4);
  1599. var src2 = SIMD.float32x4.load(src, 8);
  1600. var src3 = SIMD.float32x4.load(src, 12);
  1601. // Transpose the source matrix. Sort of. Not a true transpose operation
  1602. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1603. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1604. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1605. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1606. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1607. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1608. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1609. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1610. // This is a true transposition, but it will lead to an incorrect result
  1611. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1612. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1613. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1614. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1615. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1616. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1617. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1618. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1619. // ----
  1620. tmp1 = SIMD.float32x4.mul(row2, row3);
  1621. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1622. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1623. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1624. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1625. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1626. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1627. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1628. // ----
  1629. tmp1 = SIMD.float32x4.mul(row1, row2);
  1630. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1631. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1632. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1633. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1634. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1635. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1636. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1637. // ----
  1638. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1639. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1640. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1641. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1642. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1643. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1644. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1645. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1646. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1647. // ----
  1648. tmp1 = SIMD.float32x4.mul(row0, row1);
  1649. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1650. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1651. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1652. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1653. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1654. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1655. // ----
  1656. tmp1 = SIMD.float32x4.mul(row0, row3);
  1657. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1658. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1659. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1661. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1662. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1663. // ----
  1664. tmp1 = SIMD.float32x4.mul(row0, row2);
  1665. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1666. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1667. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1670. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1671. // Compute determinant
  1672. det = SIMD.float32x4.mul(row0, minor0);
  1673. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1674. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1675. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1676. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1677. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1678. // These shuffles aren't necessary if the faulty transposition is done
  1679. // up at the top of this function.
  1680. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1681. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1682. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1683. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1684. // Compute final values by multiplying with 1/det
  1685. minor0 = SIMD.float32x4.mul(det, minor0);
  1686. minor1 = SIMD.float32x4.mul(det, minor1);
  1687. minor2 = SIMD.float32x4.mul(det, minor2);
  1688. minor3 = SIMD.float32x4.mul(det, minor3);
  1689. SIMD.float32x4.store(dest, 0, minor0);
  1690. SIMD.float32x4.store(dest, 4, minor1);
  1691. SIMD.float32x4.store(dest, 8, minor2);
  1692. SIMD.float32x4.store(dest, 12, minor3);
  1693. return this;
  1694. };
  1695. Matrix.prototype.setTranslation = function (vector3) {
  1696. this.m[12] = vector3.x;
  1697. this.m[13] = vector3.y;
  1698. this.m[14] = vector3.z;
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiply = function (other) {
  1702. var result = new Matrix();
  1703. this.multiplyToRef(other, result);
  1704. return result;
  1705. };
  1706. Matrix.prototype.copyFrom = function (other) {
  1707. for (var index = 0; index < 16; index++) {
  1708. this.m[index] = other.m[index];
  1709. }
  1710. return this;
  1711. };
  1712. Matrix.prototype.copyToArray = function (array, offset) {
  1713. if (offset === void 0) { offset = 0; }
  1714. for (var index = 0; index < 16; index++) {
  1715. array[offset + index] = this.m[index];
  1716. }
  1717. return this;
  1718. };
  1719. Matrix.prototype.multiplyToRef = function (other, result) {
  1720. this.multiplyToArray(other, result.m, 0);
  1721. return this;
  1722. };
  1723. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1724. var tm0 = this.m[0];
  1725. var tm1 = this.m[1];
  1726. var tm2 = this.m[2];
  1727. var tm3 = this.m[3];
  1728. var tm4 = this.m[4];
  1729. var tm5 = this.m[5];
  1730. var tm6 = this.m[6];
  1731. var tm7 = this.m[7];
  1732. var tm8 = this.m[8];
  1733. var tm9 = this.m[9];
  1734. var tm10 = this.m[10];
  1735. var tm11 = this.m[11];
  1736. var tm12 = this.m[12];
  1737. var tm13 = this.m[13];
  1738. var tm14 = this.m[14];
  1739. var tm15 = this.m[15];
  1740. var om0 = other.m[0];
  1741. var om1 = other.m[1];
  1742. var om2 = other.m[2];
  1743. var om3 = other.m[3];
  1744. var om4 = other.m[4];
  1745. var om5 = other.m[5];
  1746. var om6 = other.m[6];
  1747. var om7 = other.m[7];
  1748. var om8 = other.m[8];
  1749. var om9 = other.m[9];
  1750. var om10 = other.m[10];
  1751. var om11 = other.m[11];
  1752. var om12 = other.m[12];
  1753. var om13 = other.m[13];
  1754. var om14 = other.m[14];
  1755. var om15 = other.m[15];
  1756. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1757. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1758. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1759. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1760. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1761. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1762. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1763. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1764. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1765. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1766. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1767. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1768. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1769. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1770. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1771. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1772. return this;
  1773. };
  1774. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1775. if (offset === void 0) { offset = 0; }
  1776. var tm = this.m;
  1777. var om = other.m;
  1778. var om0 = SIMD.float32x4.load(om, 0);
  1779. var om1 = SIMD.float32x4.load(om, 4);
  1780. var om2 = SIMD.float32x4.load(om, 8);
  1781. var om3 = SIMD.float32x4.load(om, 12);
  1782. var tm0 = SIMD.float32x4.load(tm, 0);
  1783. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1784. var tm1 = SIMD.float32x4.load(tm, 4);
  1785. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1786. var tm2 = SIMD.float32x4.load(tm, 8);
  1787. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1788. var tm3 = SIMD.float32x4.load(tm, 12);
  1789. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1790. };
  1791. Matrix.prototype.equals = function (value) {
  1792. return value &&
  1793. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1794. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1795. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1796. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1797. };
  1798. Matrix.prototype.clone = function () {
  1799. 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]);
  1800. };
  1801. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1802. translation.x = this.m[12];
  1803. translation.y = this.m[13];
  1804. translation.z = this.m[14];
  1805. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1806. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1807. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1808. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1809. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1810. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1811. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1812. rotation.x = 0;
  1813. rotation.y = 0;
  1814. rotation.z = 0;
  1815. rotation.w = 1;
  1816. return false;
  1817. }
  1818. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1819. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1820. return true;
  1821. };
  1822. // Statics
  1823. Matrix.FromArray = function (array, offset) {
  1824. var result = new Matrix();
  1825. if (!offset) {
  1826. offset = 0;
  1827. }
  1828. Matrix.FromArrayToRef(array, offset, result);
  1829. return result;
  1830. };
  1831. Matrix.FromArrayToRef = function (array, offset, result) {
  1832. for (var index = 0; index < 16; index++) {
  1833. result.m[index] = array[index + offset];
  1834. }
  1835. };
  1836. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1837. for (var index = 0; index < 16; index++) {
  1838. result.m[index] = array[index + offset] * scale;
  1839. }
  1840. };
  1841. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1842. result.m[0] = initialM11;
  1843. result.m[1] = initialM12;
  1844. result.m[2] = initialM13;
  1845. result.m[3] = initialM14;
  1846. result.m[4] = initialM21;
  1847. result.m[5] = initialM22;
  1848. result.m[6] = initialM23;
  1849. result.m[7] = initialM24;
  1850. result.m[8] = initialM31;
  1851. result.m[9] = initialM32;
  1852. result.m[10] = initialM33;
  1853. result.m[11] = initialM34;
  1854. result.m[12] = initialM41;
  1855. result.m[13] = initialM42;
  1856. result.m[14] = initialM43;
  1857. result.m[15] = initialM44;
  1858. };
  1859. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1860. var result = new Matrix();
  1861. result.m[0] = initialM11;
  1862. result.m[1] = initialM12;
  1863. result.m[2] = initialM13;
  1864. result.m[3] = initialM14;
  1865. result.m[4] = initialM21;
  1866. result.m[5] = initialM22;
  1867. result.m[6] = initialM23;
  1868. result.m[7] = initialM24;
  1869. result.m[8] = initialM31;
  1870. result.m[9] = initialM32;
  1871. result.m[10] = initialM33;
  1872. result.m[11] = initialM34;
  1873. result.m[12] = initialM41;
  1874. result.m[13] = initialM42;
  1875. result.m[14] = initialM43;
  1876. result.m[15] = initialM44;
  1877. return result;
  1878. };
  1879. Matrix.Compose = function (scale, rotation, translation) {
  1880. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1881. var rotationMatrix = Matrix.Identity();
  1882. rotation.toRotationMatrix(rotationMatrix);
  1883. result = result.multiply(rotationMatrix);
  1884. result.setTranslation(translation);
  1885. return result;
  1886. };
  1887. Matrix.Identity = function () {
  1888. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1889. };
  1890. Matrix.IdentityToRef = function (result) {
  1891. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1892. };
  1893. Matrix.Zero = function () {
  1894. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1895. };
  1896. Matrix.RotationX = function (angle) {
  1897. var result = new Matrix();
  1898. Matrix.RotationXToRef(angle, result);
  1899. return result;
  1900. };
  1901. Matrix.Invert = function (source) {
  1902. var result = new Matrix();
  1903. source.invertToRef(result);
  1904. return result;
  1905. };
  1906. Matrix.RotationXToRef = function (angle, result) {
  1907. var s = Math.sin(angle);
  1908. var c = Math.cos(angle);
  1909. result.m[0] = 1.0;
  1910. result.m[15] = 1.0;
  1911. result.m[5] = c;
  1912. result.m[10] = c;
  1913. result.m[9] = -s;
  1914. result.m[6] = s;
  1915. result.m[1] = 0;
  1916. result.m[2] = 0;
  1917. result.m[3] = 0;
  1918. result.m[4] = 0;
  1919. result.m[7] = 0;
  1920. result.m[8] = 0;
  1921. result.m[11] = 0;
  1922. result.m[12] = 0;
  1923. result.m[13] = 0;
  1924. result.m[14] = 0;
  1925. };
  1926. Matrix.RotationY = function (angle) {
  1927. var result = new Matrix();
  1928. Matrix.RotationYToRef(angle, result);
  1929. return result;
  1930. };
  1931. Matrix.RotationYToRef = function (angle, result) {
  1932. var s = Math.sin(angle);
  1933. var c = Math.cos(angle);
  1934. result.m[5] = 1.0;
  1935. result.m[15] = 1.0;
  1936. result.m[0] = c;
  1937. result.m[2] = -s;
  1938. result.m[8] = s;
  1939. result.m[10] = c;
  1940. result.m[1] = 0;
  1941. result.m[3] = 0;
  1942. result.m[4] = 0;
  1943. result.m[6] = 0;
  1944. result.m[7] = 0;
  1945. result.m[9] = 0;
  1946. result.m[11] = 0;
  1947. result.m[12] = 0;
  1948. result.m[13] = 0;
  1949. result.m[14] = 0;
  1950. };
  1951. Matrix.RotationZ = function (angle) {
  1952. var result = new Matrix();
  1953. Matrix.RotationZToRef(angle, result);
  1954. return result;
  1955. };
  1956. Matrix.RotationZToRef = function (angle, result) {
  1957. var s = Math.sin(angle);
  1958. var c = Math.cos(angle);
  1959. result.m[10] = 1.0;
  1960. result.m[15] = 1.0;
  1961. result.m[0] = c;
  1962. result.m[1] = s;
  1963. result.m[4] = -s;
  1964. result.m[5] = c;
  1965. result.m[2] = 0;
  1966. result.m[3] = 0;
  1967. result.m[6] = 0;
  1968. result.m[7] = 0;
  1969. result.m[8] = 0;
  1970. result.m[9] = 0;
  1971. result.m[11] = 0;
  1972. result.m[12] = 0;
  1973. result.m[13] = 0;
  1974. result.m[14] = 0;
  1975. };
  1976. Matrix.RotationAxis = function (axis, angle) {
  1977. var s = Math.sin(-angle);
  1978. var c = Math.cos(-angle);
  1979. var c1 = 1 - c;
  1980. axis.normalize();
  1981. var result = Matrix.Zero();
  1982. result.m[0] = (axis.x * axis.x) * c1 + c;
  1983. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1984. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1985. result.m[3] = 0.0;
  1986. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1987. result.m[5] = (axis.y * axis.y) * c1 + c;
  1988. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1989. result.m[7] = 0.0;
  1990. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1991. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1992. result.m[10] = (axis.z * axis.z) * c1 + c;
  1993. result.m[11] = 0.0;
  1994. result.m[15] = 1.0;
  1995. return result;
  1996. };
  1997. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1998. var result = new Matrix();
  1999. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2000. return result;
  2001. };
  2002. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2003. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2004. this._tempQuaternion.toRotationMatrix(result);
  2005. };
  2006. Matrix.Scaling = function (x, y, z) {
  2007. var result = Matrix.Zero();
  2008. Matrix.ScalingToRef(x, y, z, result);
  2009. return result;
  2010. };
  2011. Matrix.ScalingToRef = function (x, y, z, result) {
  2012. result.m[0] = x;
  2013. result.m[1] = 0;
  2014. result.m[2] = 0;
  2015. result.m[3] = 0;
  2016. result.m[4] = 0;
  2017. result.m[5] = y;
  2018. result.m[6] = 0;
  2019. result.m[7] = 0;
  2020. result.m[8] = 0;
  2021. result.m[9] = 0;
  2022. result.m[10] = z;
  2023. result.m[11] = 0;
  2024. result.m[12] = 0;
  2025. result.m[13] = 0;
  2026. result.m[14] = 0;
  2027. result.m[15] = 1.0;
  2028. };
  2029. Matrix.Translation = function (x, y, z) {
  2030. var result = Matrix.Identity();
  2031. Matrix.TranslationToRef(x, y, z, result);
  2032. return result;
  2033. };
  2034. Matrix.TranslationToRef = function (x, y, z, result) {
  2035. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2036. };
  2037. Matrix.LookAtLH = function (eye, target, up) {
  2038. var result = Matrix.Zero();
  2039. Matrix.LookAtLHToRef(eye, target, up, result);
  2040. return result;
  2041. };
  2042. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2043. // Z axis
  2044. target.subtractToRef(eye, this._zAxis);
  2045. this._zAxis.normalize();
  2046. // X axis
  2047. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2048. this._xAxis.normalize();
  2049. // Y axis
  2050. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2051. this._yAxis.normalize();
  2052. // Eye angles
  2053. var ex = -Vector3.Dot(this._xAxis, eye);
  2054. var ey = -Vector3.Dot(this._yAxis, eye);
  2055. var ez = -Vector3.Dot(this._zAxis, eye);
  2056. 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);
  2057. };
  2058. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2059. var out = result.m;
  2060. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2061. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2062. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2063. // cc.kmVec3Subtract(f, pCenter, pEye);
  2064. var f = SIMD.float32x4.sub(center, eye);
  2065. // cc.kmVec3Normalize(f, f);
  2066. var tmp = SIMD.float32x4.mul(f, f);
  2067. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2068. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2069. // cc.kmVec3Assign(up, pUp);
  2070. // cc.kmVec3Normalize(up, up);
  2071. tmp = SIMD.float32x4.mul(up, up);
  2072. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2073. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2074. // cc.kmVec3Cross(s, f, up);
  2075. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2076. // cc.kmVec3Normalize(s, s);
  2077. tmp = SIMD.float32x4.mul(s, s);
  2078. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2079. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2080. // cc.kmVec3Cross(u, s, f);
  2081. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2082. // cc.kmVec3Normalize(s, s);
  2083. tmp = SIMD.float32x4.mul(s, s);
  2084. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2085. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2086. var zero = SIMD.float32x4.splat(0.0);
  2087. s = SIMD.float32x4.neg(s);
  2088. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2089. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2090. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2091. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2092. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2093. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2094. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2095. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2096. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2097. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2098. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2099. var b3 = SIMD.float32x4.neg(eye);
  2100. b3 = SIMD.float32x4.withW(b3, 1.0);
  2101. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2102. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2103. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2104. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2105. };
  2106. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2107. var matrix = Matrix.Zero();
  2108. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2109. return matrix;
  2110. };
  2111. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2112. var hw = 2.0 / width;
  2113. var hh = 2.0 / height;
  2114. var id = 1.0 / (zfar - znear);
  2115. var nid = znear / (znear - zfar);
  2116. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2117. };
  2118. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2119. var matrix = Matrix.Zero();
  2120. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2121. return matrix;
  2122. };
  2123. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2124. result.m[0] = 2.0 / (right - left);
  2125. result.m[1] = result.m[2] = result.m[3] = 0;
  2126. result.m[5] = 2.0 / (top - bottom);
  2127. result.m[4] = result.m[6] = result.m[7] = 0;
  2128. result.m[10] = -1.0 / (znear - zfar);
  2129. result.m[8] = result.m[9] = result.m[11] = 0;
  2130. result.m[12] = (left + right) / (left - right);
  2131. result.m[13] = (top + bottom) / (bottom - top);
  2132. result.m[14] = znear / (znear - zfar);
  2133. result.m[15] = 1.0;
  2134. };
  2135. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2136. var matrix = Matrix.Zero();
  2137. matrix.m[0] = (2.0 * znear) / width;
  2138. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2139. matrix.m[5] = (2.0 * znear) / height;
  2140. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2141. matrix.m[10] = -zfar / (znear - zfar);
  2142. matrix.m[8] = matrix.m[9] = 0.0;
  2143. matrix.m[11] = 1.0;
  2144. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2145. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2146. return matrix;
  2147. };
  2148. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2149. var matrix = Matrix.Zero();
  2150. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2151. return matrix;
  2152. };
  2153. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2154. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2155. var tan = 1.0 / (Math.tan(fov * 0.5));
  2156. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2157. if (v_fixed) {
  2158. result.m[0] = tan / aspect;
  2159. }
  2160. else {
  2161. result.m[0] = tan;
  2162. }
  2163. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2164. if (v_fixed) {
  2165. result.m[5] = tan;
  2166. }
  2167. else {
  2168. result.m[5] = tan * aspect;
  2169. }
  2170. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2171. result.m[8] = result.m[9] = 0.0;
  2172. result.m[10] = -zfar / (znear - zfar);
  2173. result.m[11] = 1.0;
  2174. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2175. result.m[14] = (znear * zfar) / (znear - zfar);
  2176. };
  2177. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2178. var cw = viewport.width;
  2179. var ch = viewport.height;
  2180. var cx = viewport.x;
  2181. var cy = viewport.y;
  2182. 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);
  2183. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2184. };
  2185. Matrix.GetAsMatrix2x2 = function (matrix) {
  2186. return new Float32Array([
  2187. matrix.m[0], matrix.m[1],
  2188. matrix.m[4], matrix.m[5]
  2189. ]);
  2190. };
  2191. Matrix.GetAsMatrix3x3 = function (matrix) {
  2192. return new Float32Array([
  2193. matrix.m[0], matrix.m[1], matrix.m[2],
  2194. matrix.m[4], matrix.m[5], matrix.m[6],
  2195. matrix.m[8], matrix.m[9], matrix.m[10]
  2196. ]);
  2197. };
  2198. Matrix.Transpose = function (matrix) {
  2199. var result = new Matrix();
  2200. result.m[0] = matrix.m[0];
  2201. result.m[1] = matrix.m[4];
  2202. result.m[2] = matrix.m[8];
  2203. result.m[3] = matrix.m[12];
  2204. result.m[4] = matrix.m[1];
  2205. result.m[5] = matrix.m[5];
  2206. result.m[6] = matrix.m[9];
  2207. result.m[7] = matrix.m[13];
  2208. result.m[8] = matrix.m[2];
  2209. result.m[9] = matrix.m[6];
  2210. result.m[10] = matrix.m[10];
  2211. result.m[11] = matrix.m[14];
  2212. result.m[12] = matrix.m[3];
  2213. result.m[13] = matrix.m[7];
  2214. result.m[14] = matrix.m[11];
  2215. result.m[15] = matrix.m[15];
  2216. return result;
  2217. };
  2218. Matrix.Reflection = function (plane) {
  2219. var matrix = new Matrix();
  2220. Matrix.ReflectionToRef(plane, matrix);
  2221. return matrix;
  2222. };
  2223. Matrix.ReflectionToRef = function (plane, result) {
  2224. plane.normalize();
  2225. var x = plane.normal.x;
  2226. var y = plane.normal.y;
  2227. var z = plane.normal.z;
  2228. var temp = -2 * x;
  2229. var temp2 = -2 * y;
  2230. var temp3 = -2 * z;
  2231. result.m[0] = (temp * x) + 1;
  2232. result.m[1] = temp2 * x;
  2233. result.m[2] = temp3 * x;
  2234. result.m[3] = 0.0;
  2235. result.m[4] = temp * y;
  2236. result.m[5] = (temp2 * y) + 1;
  2237. result.m[6] = temp3 * y;
  2238. result.m[7] = 0.0;
  2239. result.m[8] = temp * z;
  2240. result.m[9] = temp2 * z;
  2241. result.m[10] = (temp3 * z) + 1;
  2242. result.m[11] = 0.0;
  2243. result.m[12] = temp * plane.d;
  2244. result.m[13] = temp2 * plane.d;
  2245. result.m[14] = temp3 * plane.d;
  2246. result.m[15] = 1.0;
  2247. };
  2248. Matrix._tempQuaternion = new Quaternion();
  2249. Matrix._xAxis = Vector3.Zero();
  2250. Matrix._yAxis = Vector3.Zero();
  2251. Matrix._zAxis = Vector3.Zero();
  2252. return Matrix;
  2253. })();
  2254. BABYLON.Matrix = Matrix;
  2255. var Plane = (function () {
  2256. function Plane(a, b, c, d) {
  2257. this.normal = new Vector3(a, b, c);
  2258. this.d = d;
  2259. }
  2260. Plane.prototype.asArray = function () {
  2261. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2262. };
  2263. // Methods
  2264. Plane.prototype.clone = function () {
  2265. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2266. };
  2267. Plane.prototype.normalize = function () {
  2268. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2269. var magnitude = 0;
  2270. if (norm !== 0) {
  2271. magnitude = 1.0 / norm;
  2272. }
  2273. this.normal.x *= magnitude;
  2274. this.normal.y *= magnitude;
  2275. this.normal.z *= magnitude;
  2276. this.d *= magnitude;
  2277. return this;
  2278. };
  2279. Plane.prototype.transform = function (transformation) {
  2280. var transposedMatrix = Matrix.Transpose(transformation);
  2281. var x = this.normal.x;
  2282. var y = this.normal.y;
  2283. var z = this.normal.z;
  2284. var d = this.d;
  2285. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2286. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2287. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2288. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2289. return new Plane(normalX, normalY, normalZ, finalD);
  2290. };
  2291. Plane.prototype.dotCoordinate = function (point) {
  2292. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2293. };
  2294. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2295. var x1 = point2.x - point1.x;
  2296. var y1 = point2.y - point1.y;
  2297. var z1 = point2.z - point1.z;
  2298. var x2 = point3.x - point1.x;
  2299. var y2 = point3.y - point1.y;
  2300. var z2 = point3.z - point1.z;
  2301. var yz = (y1 * z2) - (z1 * y2);
  2302. var xz = (z1 * x2) - (x1 * z2);
  2303. var xy = (x1 * y2) - (y1 * x2);
  2304. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2305. var invPyth;
  2306. if (pyth !== 0) {
  2307. invPyth = 1.0 / pyth;
  2308. }
  2309. else {
  2310. invPyth = 0;
  2311. }
  2312. this.normal.x = yz * invPyth;
  2313. this.normal.y = xz * invPyth;
  2314. this.normal.z = xy * invPyth;
  2315. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2316. return this;
  2317. };
  2318. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2319. var dot = Vector3.Dot(this.normal, direction);
  2320. return (dot <= epsilon);
  2321. };
  2322. Plane.prototype.signedDistanceTo = function (point) {
  2323. return Vector3.Dot(point, this.normal) + this.d;
  2324. };
  2325. // Statics
  2326. Plane.FromArray = function (array) {
  2327. return new Plane(array[0], array[1], array[2], array[3]);
  2328. };
  2329. Plane.FromPoints = function (point1, point2, point3) {
  2330. var result = new Plane(0, 0, 0, 0);
  2331. result.copyFromPoints(point1, point2, point3);
  2332. return result;
  2333. };
  2334. Plane.FromPositionAndNormal = function (origin, normal) {
  2335. var result = new Plane(0, 0, 0, 0);
  2336. normal.normalize();
  2337. result.normal = normal;
  2338. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2339. return result;
  2340. };
  2341. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2342. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2343. return Vector3.Dot(point, normal) + d;
  2344. };
  2345. return Plane;
  2346. })();
  2347. BABYLON.Plane = Plane;
  2348. var Viewport = (function () {
  2349. function Viewport(x, y, width, height) {
  2350. this.x = x;
  2351. this.y = y;
  2352. this.width = width;
  2353. this.height = height;
  2354. }
  2355. Viewport.prototype.toGlobal = function (engine) {
  2356. var width = engine.getRenderWidth();
  2357. var height = engine.getRenderHeight();
  2358. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2359. };
  2360. return Viewport;
  2361. })();
  2362. BABYLON.Viewport = Viewport;
  2363. var Frustum = (function () {
  2364. function Frustum() {
  2365. }
  2366. Frustum.GetPlanes = function (transform) {
  2367. var frustumPlanes = [];
  2368. for (var index = 0; index < 6; index++) {
  2369. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2370. }
  2371. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2372. return frustumPlanes;
  2373. };
  2374. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2375. // Near
  2376. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2377. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2378. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2379. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2380. frustumPlanes[0].normalize();
  2381. // Far
  2382. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2383. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2384. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2385. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2386. frustumPlanes[1].normalize();
  2387. // Left
  2388. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2389. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2390. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2391. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2392. frustumPlanes[2].normalize();
  2393. // Right
  2394. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2395. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2396. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2397. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2398. frustumPlanes[3].normalize();
  2399. // Top
  2400. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2401. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2402. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2403. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2404. frustumPlanes[4].normalize();
  2405. // Bottom
  2406. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2407. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2408. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2409. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2410. frustumPlanes[5].normalize();
  2411. };
  2412. return Frustum;
  2413. })();
  2414. BABYLON.Frustum = Frustum;
  2415. var Ray = (function () {
  2416. function Ray(origin, direction, length) {
  2417. if (length === void 0) { length = Number.MAX_VALUE; }
  2418. this.origin = origin;
  2419. this.direction = direction;
  2420. this.length = length;
  2421. }
  2422. // Methods
  2423. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2424. var d = 0.0;
  2425. var maxValue = Number.MAX_VALUE;
  2426. var inv;
  2427. var min;
  2428. var max;
  2429. var temp;
  2430. if (Math.abs(this.direction.x) < 0.0000001) {
  2431. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2432. return false;
  2433. }
  2434. }
  2435. else {
  2436. inv = 1.0 / this.direction.x;
  2437. min = (minimum.x - this.origin.x) * inv;
  2438. max = (maximum.x - this.origin.x) * inv;
  2439. if (max === -Infinity) {
  2440. max = Infinity;
  2441. }
  2442. if (min > max) {
  2443. temp = min;
  2444. min = max;
  2445. max = temp;
  2446. }
  2447. d = Math.max(min, d);
  2448. maxValue = Math.min(max, maxValue);
  2449. if (d > maxValue) {
  2450. return false;
  2451. }
  2452. }
  2453. if (Math.abs(this.direction.y) < 0.0000001) {
  2454. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2455. return false;
  2456. }
  2457. }
  2458. else {
  2459. inv = 1.0 / this.direction.y;
  2460. min = (minimum.y - this.origin.y) * inv;
  2461. max = (maximum.y - this.origin.y) * inv;
  2462. if (max === -Infinity) {
  2463. max = Infinity;
  2464. }
  2465. if (min > max) {
  2466. temp = min;
  2467. min = max;
  2468. max = temp;
  2469. }
  2470. d = Math.max(min, d);
  2471. maxValue = Math.min(max, maxValue);
  2472. if (d > maxValue) {
  2473. return false;
  2474. }
  2475. }
  2476. if (Math.abs(this.direction.z) < 0.0000001) {
  2477. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2478. return false;
  2479. }
  2480. }
  2481. else {
  2482. inv = 1.0 / this.direction.z;
  2483. min = (minimum.z - this.origin.z) * inv;
  2484. max = (maximum.z - this.origin.z) * inv;
  2485. if (max === -Infinity) {
  2486. max = Infinity;
  2487. }
  2488. if (min > max) {
  2489. temp = min;
  2490. min = max;
  2491. max = temp;
  2492. }
  2493. d = Math.max(min, d);
  2494. maxValue = Math.min(max, maxValue);
  2495. if (d > maxValue) {
  2496. return false;
  2497. }
  2498. }
  2499. return true;
  2500. };
  2501. Ray.prototype.intersectsBox = function (box) {
  2502. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2503. };
  2504. Ray.prototype.intersectsSphere = function (sphere) {
  2505. var x = sphere.center.x - this.origin.x;
  2506. var y = sphere.center.y - this.origin.y;
  2507. var z = sphere.center.z - this.origin.z;
  2508. var pyth = (x * x) + (y * y) + (z * z);
  2509. var rr = sphere.radius * sphere.radius;
  2510. if (pyth <= rr) {
  2511. return true;
  2512. }
  2513. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2514. if (dot < 0.0) {
  2515. return false;
  2516. }
  2517. var temp = pyth - (dot * dot);
  2518. return temp <= rr;
  2519. };
  2520. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2521. if (!this._edge1) {
  2522. this._edge1 = Vector3.Zero();
  2523. this._edge2 = Vector3.Zero();
  2524. this._pvec = Vector3.Zero();
  2525. this._tvec = Vector3.Zero();
  2526. this._qvec = Vector3.Zero();
  2527. }
  2528. vertex1.subtractToRef(vertex0, this._edge1);
  2529. vertex2.subtractToRef(vertex0, this._edge2);
  2530. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2531. var det = Vector3.Dot(this._edge1, this._pvec);
  2532. if (det === 0) {
  2533. return null;
  2534. }
  2535. var invdet = 1 / det;
  2536. this.origin.subtractToRef(vertex0, this._tvec);
  2537. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2538. if (bu < 0 || bu > 1.0) {
  2539. return null;
  2540. }
  2541. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2542. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2543. if (bv < 0 || bu + bv > 1.0) {
  2544. return null;
  2545. }
  2546. //check if the distance is longer than the predefined length.
  2547. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2548. if (distance > this.length) {
  2549. return null;
  2550. }
  2551. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2552. };
  2553. // Statics
  2554. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2555. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2556. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2557. var direction = end.subtract(start);
  2558. direction.normalize();
  2559. return new Ray(start, direction);
  2560. };
  2561. /**
  2562. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2563. * transformed to the given world matrix.
  2564. * @param origin The origin point
  2565. * @param end The end point
  2566. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2567. */
  2568. Ray.CreateNewFromTo = function (origin, end, world) {
  2569. if (world === void 0) { world = Matrix.Identity(); }
  2570. var direction = end.subtract(origin);
  2571. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2572. direction.normalize();
  2573. return Ray.Transform(new Ray(origin, direction, length), world);
  2574. };
  2575. Ray.Transform = function (ray, matrix) {
  2576. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2577. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2578. return new Ray(newOrigin, newDirection, ray.length);
  2579. };
  2580. return Ray;
  2581. })();
  2582. BABYLON.Ray = Ray;
  2583. (function (Space) {
  2584. Space[Space["LOCAL"] = 0] = "LOCAL";
  2585. Space[Space["WORLD"] = 1] = "WORLD";
  2586. })(BABYLON.Space || (BABYLON.Space = {}));
  2587. var Space = BABYLON.Space;
  2588. var Axis = (function () {
  2589. function Axis() {
  2590. }
  2591. Axis.X = new Vector3(1, 0, 0);
  2592. Axis.Y = new Vector3(0, 1, 0);
  2593. Axis.Z = new Vector3(0, 0, 1);
  2594. return Axis;
  2595. })();
  2596. BABYLON.Axis = Axis;
  2597. ;
  2598. var BezierCurve = (function () {
  2599. function BezierCurve() {
  2600. }
  2601. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2602. // Extract X (which is equal to time here)
  2603. var f0 = 1 - 3 * x2 + 3 * x1;
  2604. var f1 = 3 * x2 - 6 * x1;
  2605. var f2 = 3 * x1;
  2606. var refinedT = t;
  2607. for (var i = 0; i < 5; i++) {
  2608. var refinedT2 = refinedT * refinedT;
  2609. var refinedT3 = refinedT2 * refinedT;
  2610. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2611. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2612. refinedT -= (x - t) * slope;
  2613. refinedT = Math.min(1, Math.max(0, refinedT));
  2614. }
  2615. // Resolve cubic bezier for the given x
  2616. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2617. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2618. Math.pow(refinedT, 3);
  2619. };
  2620. return BezierCurve;
  2621. })();
  2622. BABYLON.BezierCurve = BezierCurve;
  2623. (function (Orientation) {
  2624. Orientation[Orientation["CW"] = 0] = "CW";
  2625. Orientation[Orientation["CCW"] = 1] = "CCW";
  2626. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2627. var Orientation = BABYLON.Orientation;
  2628. var Angle = (function () {
  2629. function Angle(radians) {
  2630. var _this = this;
  2631. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2632. this.radians = function () { return _this._radians; };
  2633. this._radians = radians;
  2634. if (this._radians < 0)
  2635. this._radians += (2 * Math.PI);
  2636. }
  2637. Angle.BetweenTwoPoints = function (a, b) {
  2638. var delta = b.subtract(a);
  2639. var theta = Math.atan2(delta.y, delta.x);
  2640. return new Angle(theta);
  2641. };
  2642. Angle.FromRadians = function (radians) {
  2643. return new Angle(radians);
  2644. };
  2645. Angle.FromDegrees = function (degrees) {
  2646. return new Angle(degrees * Math.PI / 180);
  2647. };
  2648. return Angle;
  2649. })();
  2650. BABYLON.Angle = Angle;
  2651. var Arc2 = (function () {
  2652. function Arc2(startPoint, midPoint, endPoint) {
  2653. this.startPoint = startPoint;
  2654. this.midPoint = midPoint;
  2655. this.endPoint = endPoint;
  2656. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2657. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2658. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2659. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2660. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2661. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2662. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2663. var a1 = this.startAngle.degrees();
  2664. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2665. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2666. // angles correction
  2667. if (a2 - a1 > +180.0)
  2668. a2 -= 360.0;
  2669. if (a2 - a1 < -180.0)
  2670. a2 += 360.0;
  2671. if (a3 - a2 > +180.0)
  2672. a3 -= 360.0;
  2673. if (a3 - a2 < -180.0)
  2674. a3 += 360.0;
  2675. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2676. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2677. }
  2678. return Arc2;
  2679. })();
  2680. BABYLON.Arc2 = Arc2;
  2681. var PathCursor = (function () {
  2682. function PathCursor(path) {
  2683. this.path = path;
  2684. this._onchange = new Array();
  2685. this.value = 0;
  2686. this.animations = new Array();
  2687. }
  2688. PathCursor.prototype.getPoint = function () {
  2689. var point = this.path.getPointAtLengthPosition(this.value);
  2690. return new Vector3(point.x, 0, point.y);
  2691. };
  2692. PathCursor.prototype.moveAhead = function (step) {
  2693. if (step === void 0) { step = 0.002; }
  2694. this.move(step);
  2695. return this;
  2696. };
  2697. PathCursor.prototype.moveBack = function (step) {
  2698. if (step === void 0) { step = 0.002; }
  2699. this.move(-step);
  2700. return this;
  2701. };
  2702. PathCursor.prototype.move = function (step) {
  2703. if (Math.abs(step) > 1) {
  2704. throw "step size should be less than 1.";
  2705. }
  2706. this.value += step;
  2707. this.ensureLimits();
  2708. this.raiseOnChange();
  2709. return this;
  2710. };
  2711. PathCursor.prototype.ensureLimits = function () {
  2712. while (this.value > 1) {
  2713. this.value -= 1;
  2714. }
  2715. while (this.value < 0) {
  2716. this.value += 1;
  2717. }
  2718. return this;
  2719. };
  2720. // used by animation engine
  2721. PathCursor.prototype.markAsDirty = function (propertyName) {
  2722. this.ensureLimits();
  2723. this.raiseOnChange();
  2724. return this;
  2725. };
  2726. PathCursor.prototype.raiseOnChange = function () {
  2727. var _this = this;
  2728. this._onchange.forEach(function (f) { return f(_this); });
  2729. return this;
  2730. };
  2731. PathCursor.prototype.onchange = function (f) {
  2732. this._onchange.push(f);
  2733. return this;
  2734. };
  2735. return PathCursor;
  2736. })();
  2737. BABYLON.PathCursor = PathCursor;
  2738. var Path2 = (function () {
  2739. function Path2(x, y) {
  2740. this._points = new Array();
  2741. this._length = 0;
  2742. this.closed = false;
  2743. this._points.push(new Vector2(x, y));
  2744. }
  2745. Path2.prototype.addLineTo = function (x, y) {
  2746. if (closed) {
  2747. BABYLON.Tools.Error("cannot add lines to closed paths");
  2748. return this;
  2749. }
  2750. var newPoint = new Vector2(x, y);
  2751. var previousPoint = this._points[this._points.length - 1];
  2752. this._points.push(newPoint);
  2753. this._length += newPoint.subtract(previousPoint).length();
  2754. return this;
  2755. };
  2756. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2757. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2758. if (closed) {
  2759. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2760. return this;
  2761. }
  2762. var startPoint = this._points[this._points.length - 1];
  2763. var midPoint = new Vector2(midX, midY);
  2764. var endPoint = new Vector2(endX, endY);
  2765. var arc = new Arc2(startPoint, midPoint, endPoint);
  2766. var increment = arc.angle.radians() / numberOfSegments;
  2767. if (arc.orientation === Orientation.CW)
  2768. increment *= -1;
  2769. var currentAngle = arc.startAngle.radians() + increment;
  2770. for (var i = 0; i < numberOfSegments; i++) {
  2771. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2772. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2773. this.addLineTo(x, y);
  2774. currentAngle += increment;
  2775. }
  2776. return this;
  2777. };
  2778. Path2.prototype.close = function () {
  2779. this.closed = true;
  2780. return this;
  2781. };
  2782. Path2.prototype.length = function () {
  2783. var result = this._length;
  2784. if (!this.closed) {
  2785. var lastPoint = this._points[this._points.length - 1];
  2786. var firstPoint = this._points[0];
  2787. result += (firstPoint.subtract(lastPoint).length());
  2788. }
  2789. return result;
  2790. };
  2791. Path2.prototype.getPoints = function () {
  2792. return this._points;
  2793. };
  2794. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2795. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2796. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2797. return Vector2.Zero();
  2798. }
  2799. var lengthPosition = normalizedLengthPosition * this.length();
  2800. var previousOffset = 0;
  2801. for (var i = 0; i < this._points.length; i++) {
  2802. var j = (i + 1) % this._points.length;
  2803. var a = this._points[i];
  2804. var b = this._points[j];
  2805. var bToA = b.subtract(a);
  2806. var nextOffset = (bToA.length() + previousOffset);
  2807. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2808. var dir = bToA.normalize();
  2809. var localOffset = lengthPosition - previousOffset;
  2810. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2811. }
  2812. previousOffset = nextOffset;
  2813. }
  2814. BABYLON.Tools.Error("internal error");
  2815. return Vector2.Zero();
  2816. };
  2817. Path2.StartingAt = function (x, y) {
  2818. return new Path2(x, y);
  2819. };
  2820. return Path2;
  2821. })();
  2822. BABYLON.Path2 = Path2;
  2823. var Path3D = (function () {
  2824. function Path3D(path, firstNormal) {
  2825. this.path = path;
  2826. this._curve = new Array();
  2827. this._distances = new Array();
  2828. this._tangents = new Array();
  2829. this._normals = new Array();
  2830. this._binormals = new Array();
  2831. for (var p = 0; p < path.length; p++) {
  2832. this._curve[p] = path[p].clone(); // hard copy
  2833. }
  2834. this._compute(firstNormal);
  2835. }
  2836. Path3D.prototype.getCurve = function () {
  2837. return this._curve;
  2838. };
  2839. Path3D.prototype.getTangents = function () {
  2840. return this._tangents;
  2841. };
  2842. Path3D.prototype.getNormals = function () {
  2843. return this._normals;
  2844. };
  2845. Path3D.prototype.getBinormals = function () {
  2846. return this._binormals;
  2847. };
  2848. Path3D.prototype.getDistances = function () {
  2849. return this._distances;
  2850. };
  2851. Path3D.prototype.update = function (path, firstNormal) {
  2852. for (var p = 0; p < path.length; p++) {
  2853. this._curve[p].x = path[p].x;
  2854. this._curve[p].y = path[p].y;
  2855. this._curve[p].z = path[p].z;
  2856. }
  2857. this._compute(firstNormal);
  2858. return this;
  2859. };
  2860. // private function compute() : computes tangents, normals and binormals
  2861. Path3D.prototype._compute = function (firstNormal) {
  2862. var l = this._curve.length;
  2863. // first and last tangents
  2864. this._tangents[0] = this._getFirstNonNullVector(0);
  2865. this._tangents[0].normalize();
  2866. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2867. this._tangents[l - 1].normalize();
  2868. // normals and binormals at first point : arbitrary vector with _normalVector()
  2869. var tg0 = this._tangents[0];
  2870. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2871. this._normals[0] = pp0;
  2872. this._normals[0].normalize();
  2873. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2874. this._binormals[0].normalize();
  2875. this._distances[0] = 0;
  2876. // normals and binormals : next points
  2877. var prev; // previous vector (segment)
  2878. var cur; // current vector (segment)
  2879. var curTang; // current tangent
  2880. // previous normal
  2881. var prevBinor; // previous binormal
  2882. for (var i = 1; i < l; i++) {
  2883. // tangents
  2884. prev = this._getLastNonNullVector(i);
  2885. if (i < l - 1) {
  2886. cur = this._getFirstNonNullVector(i);
  2887. this._tangents[i] = prev.add(cur);
  2888. this._tangents[i].normalize();
  2889. }
  2890. this._distances[i] = this._distances[i - 1] + prev.length();
  2891. // normals and binormals
  2892. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2893. curTang = this._tangents[i];
  2894. prevBinor = this._binormals[i - 1];
  2895. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2896. this._normals[i].normalize();
  2897. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2898. this._binormals[i].normalize();
  2899. }
  2900. };
  2901. // private function getFirstNonNullVector(index)
  2902. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2903. Path3D.prototype._getFirstNonNullVector = function (index) {
  2904. var i = 1;
  2905. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2906. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2907. i++;
  2908. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2909. }
  2910. return nNVector;
  2911. };
  2912. // private function getLastNonNullVector(index)
  2913. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2914. Path3D.prototype._getLastNonNullVector = function (index) {
  2915. var i = 1;
  2916. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2917. while (nLVector.length() === 0 && index > i + 1) {
  2918. i++;
  2919. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2920. }
  2921. return nLVector;
  2922. };
  2923. // private function normalVector(v0, vt, va) :
  2924. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2925. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2926. Path3D.prototype._normalVector = function (v0, vt, va) {
  2927. var normal0;
  2928. if (va === undefined || va === null) {
  2929. var point;
  2930. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2931. point = new Vector3(0, -1, 0);
  2932. }
  2933. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2934. point = new Vector3(1, 0, 0);
  2935. }
  2936. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2937. point = new Vector3(0, 0, 1);
  2938. }
  2939. normal0 = Vector3.Cross(vt, point);
  2940. }
  2941. else {
  2942. normal0 = Vector3.Cross(vt, va);
  2943. Vector3.CrossToRef(normal0, vt, normal0);
  2944. }
  2945. normal0.normalize();
  2946. return normal0;
  2947. };
  2948. return Path3D;
  2949. })();
  2950. BABYLON.Path3D = Path3D;
  2951. var Curve3 = (function () {
  2952. function Curve3(points) {
  2953. this._length = 0;
  2954. this._points = points;
  2955. this._length = this._computeLength(points);
  2956. }
  2957. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2958. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2959. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2960. var bez = new Array();
  2961. var equation = function (t, val0, val1, val2) {
  2962. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2963. return res;
  2964. };
  2965. for (var i = 0; i <= nbPoints; i++) {
  2966. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2967. }
  2968. return new Curve3(bez);
  2969. };
  2970. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2971. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2972. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2973. var bez = new Array();
  2974. var equation = function (t, val0, val1, val2, val3) {
  2975. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2976. return res;
  2977. };
  2978. for (var i = 0; i <= nbPoints; i++) {
  2979. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2980. }
  2981. return new Curve3(bez);
  2982. };
  2983. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2984. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2985. var hermite = new Array();
  2986. var step = 1 / nbPoints;
  2987. for (var i = 0; i <= nbPoints; i++) {
  2988. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2989. }
  2990. return new Curve3(hermite);
  2991. };
  2992. Curve3.prototype.getPoints = function () {
  2993. return this._points;
  2994. };
  2995. Curve3.prototype.length = function () {
  2996. return this._length;
  2997. };
  2998. Curve3.prototype.continue = function (curve) {
  2999. var lastPoint = this._points[this._points.length - 1];
  3000. var continuedPoints = this._points.slice();
  3001. var curvePoints = curve.getPoints();
  3002. for (var i = 1; i < curvePoints.length; i++) {
  3003. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3004. }
  3005. var continuedCurve = new Curve3(continuedPoints);
  3006. return continuedCurve;
  3007. };
  3008. Curve3.prototype._computeLength = function (path) {
  3009. var l = 0;
  3010. for (var i = 1; i < path.length; i++) {
  3011. l += (path[i].subtract(path[i - 1])).length();
  3012. }
  3013. return l;
  3014. };
  3015. return Curve3;
  3016. })();
  3017. BABYLON.Curve3 = Curve3;
  3018. // Vertex formats
  3019. var PositionNormalVertex = (function () {
  3020. function PositionNormalVertex(position, normal) {
  3021. if (position === void 0) { position = Vector3.Zero(); }
  3022. if (normal === void 0) { normal = Vector3.Up(); }
  3023. this.position = position;
  3024. this.normal = normal;
  3025. }
  3026. PositionNormalVertex.prototype.clone = function () {
  3027. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3028. };
  3029. return PositionNormalVertex;
  3030. })();
  3031. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3032. var PositionNormalTextureVertex = (function () {
  3033. function PositionNormalTextureVertex(position, normal, uv) {
  3034. if (position === void 0) { position = Vector3.Zero(); }
  3035. if (normal === void 0) { normal = Vector3.Up(); }
  3036. if (uv === void 0) { uv = Vector2.Zero(); }
  3037. this.position = position;
  3038. this.normal = normal;
  3039. this.uv = uv;
  3040. }
  3041. PositionNormalTextureVertex.prototype.clone = function () {
  3042. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3043. };
  3044. return PositionNormalTextureVertex;
  3045. })();
  3046. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3047. // SIMD
  3048. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3049. var previousInvertToRef = Matrix.prototype.invertToRef;
  3050. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3051. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3052. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3053. var SIMDHelper = (function () {
  3054. function SIMDHelper() {
  3055. }
  3056. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3057. get: function () {
  3058. return SIMDHelper._isEnabled;
  3059. },
  3060. enumerable: true,
  3061. configurable: true
  3062. });
  3063. SIMDHelper.DisableSIMD = function () {
  3064. // Replace functions
  3065. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3066. Matrix.prototype.invertToRef = previousInvertToRef;
  3067. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3068. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3069. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3070. SIMDHelper._isEnabled = false;
  3071. };
  3072. SIMDHelper.EnableSIMD = function () {
  3073. if (window.SIMD === undefined) {
  3074. return;
  3075. }
  3076. // Replace functions
  3077. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3078. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3079. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3080. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3081. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3082. Object.defineProperty(Vector3.prototype, "x", {
  3083. get: function () { return this._data[0]; },
  3084. set: function (value) {
  3085. if (!this._data) {
  3086. this._data = new Float32Array(3);
  3087. }
  3088. this._data[0] = value;
  3089. }
  3090. });
  3091. Object.defineProperty(Vector3.prototype, "y", {
  3092. get: function () { return this._data[1]; },
  3093. set: function (value) {
  3094. this._data[1] = value;
  3095. }
  3096. });
  3097. Object.defineProperty(Vector3.prototype, "z", {
  3098. get: function () { return this._data[2]; },
  3099. set: function (value) {
  3100. this._data[2] = value;
  3101. }
  3102. });
  3103. SIMDHelper._isEnabled = true;
  3104. };
  3105. SIMDHelper._isEnabled = false;
  3106. return SIMDHelper;
  3107. })();
  3108. BABYLON.SIMDHelper = SIMDHelper;
  3109. })(BABYLON || (BABYLON = {}));
  3110. var BABYLON;
  3111. (function (BABYLON) {
  3112. var Database = (function () {
  3113. function Database(urlToScene, callbackManifestChecked) {
  3114. // Handling various flavors of prefixed version of IndexedDB
  3115. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3116. this.callbackManifestChecked = callbackManifestChecked;
  3117. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3118. this.db = null;
  3119. this.enableSceneOffline = false;
  3120. this.enableTexturesOffline = false;
  3121. this.manifestVersionFound = 0;
  3122. this.mustUpdateRessources = false;
  3123. this.hasReachedQuota = false;
  3124. if (!Database.IDBStorageEnabled) {
  3125. this.callbackManifestChecked(true);
  3126. }
  3127. else {
  3128. this.checkManifestFile();
  3129. }
  3130. }
  3131. Database.prototype.checkManifestFile = function () {
  3132. var _this = this;
  3133. function noManifestFile() {
  3134. that.enableSceneOffline = false;
  3135. that.enableTexturesOffline = false;
  3136. that.callbackManifestChecked(false);
  3137. }
  3138. var that = this;
  3139. var manifestURL = this.currentSceneUrl + ".manifest";
  3140. var xhr = new XMLHttpRequest();
  3141. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3142. xhr.open("GET", manifestURLTimeStamped, true);
  3143. xhr.addEventListener("load", function () {
  3144. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3145. try {
  3146. var manifestFile = JSON.parse(xhr.response);
  3147. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3148. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3149. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3150. _this.manifestVersionFound = manifestFile.version;
  3151. }
  3152. if (_this.callbackManifestChecked) {
  3153. _this.callbackManifestChecked(true);
  3154. }
  3155. }
  3156. catch (ex) {
  3157. noManifestFile();
  3158. }
  3159. }
  3160. else {
  3161. noManifestFile();
  3162. }
  3163. }, false);
  3164. xhr.addEventListener("error", function (event) {
  3165. noManifestFile();
  3166. }, false);
  3167. try {
  3168. xhr.send();
  3169. }
  3170. catch (ex) {
  3171. BABYLON.Tools.Error("Error on XHR send request.");
  3172. that.callbackManifestChecked(false);
  3173. }
  3174. };
  3175. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3176. var _this = this;
  3177. function handleError() {
  3178. that.isSupported = false;
  3179. if (errorCallback)
  3180. errorCallback();
  3181. }
  3182. var that = this;
  3183. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3184. // Your browser doesn't support IndexedDB
  3185. this.isSupported = false;
  3186. if (errorCallback)
  3187. errorCallback();
  3188. }
  3189. else {
  3190. // If the DB hasn't been opened or created yet
  3191. if (!this.db) {
  3192. this.hasReachedQuota = false;
  3193. this.isSupported = true;
  3194. var request = this.idbFactory.open("babylonjs", 1);
  3195. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3196. request.onerror = function (event) {
  3197. handleError();
  3198. };
  3199. // executes when a version change transaction cannot complete due to other active transactions
  3200. request.onblocked = function (event) {
  3201. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3202. handleError();
  3203. };
  3204. // DB has been opened successfully
  3205. request.onsuccess = function (event) {
  3206. _this.db = request.result;
  3207. successCallback();
  3208. };
  3209. // Initialization of the DB. Creating Scenes & Textures stores
  3210. request.onupgradeneeded = function (event) {
  3211. _this.db = (event.target).result;
  3212. try {
  3213. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3214. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3215. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3216. }
  3217. catch (ex) {
  3218. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3219. handleError();
  3220. }
  3221. };
  3222. }
  3223. else {
  3224. if (successCallback)
  3225. successCallback();
  3226. }
  3227. }
  3228. };
  3229. Database.prototype.loadImageFromDB = function (url, image) {
  3230. var _this = this;
  3231. var completeURL = Database.ReturnFullUrlLocation(url);
  3232. var saveAndLoadImage = function () {
  3233. if (!_this.hasReachedQuota && _this.db !== null) {
  3234. // the texture is not yet in the DB, let's try to save it
  3235. _this._saveImageIntoDBAsync(completeURL, image);
  3236. }
  3237. else {
  3238. image.src = url;
  3239. }
  3240. };
  3241. if (!this.mustUpdateRessources) {
  3242. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3243. }
  3244. else {
  3245. saveAndLoadImage();
  3246. }
  3247. };
  3248. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3249. if (this.isSupported && this.db !== null) {
  3250. var texture;
  3251. var transaction = this.db.transaction(["textures"]);
  3252. transaction.onabort = function (event) {
  3253. image.src = url;
  3254. };
  3255. transaction.oncomplete = function (event) {
  3256. var blobTextureURL;
  3257. if (texture) {
  3258. var URL = window.URL || window.webkitURL;
  3259. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3260. image.onerror = function () {
  3261. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3262. image.src = url;
  3263. };
  3264. image.src = blobTextureURL;
  3265. }
  3266. else {
  3267. notInDBCallback();
  3268. }
  3269. };
  3270. var getRequest = transaction.objectStore("textures").get(url);
  3271. getRequest.onsuccess = function (event) {
  3272. texture = (event.target).result;
  3273. };
  3274. getRequest.onerror = function (event) {
  3275. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3276. image.src = url;
  3277. };
  3278. }
  3279. else {
  3280. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3281. image.src = url;
  3282. }
  3283. };
  3284. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3285. var _this = this;
  3286. if (this.isSupported) {
  3287. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3288. var generateBlobUrl = function () {
  3289. var blobTextureURL;
  3290. if (blob) {
  3291. var URL = window.URL || window.webkitURL;
  3292. try {
  3293. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3294. }
  3295. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3296. catch (ex) {
  3297. blobTextureURL = URL.createObjectURL(blob);
  3298. }
  3299. }
  3300. image.src = blobTextureURL;
  3301. };
  3302. if (Database.IsUASupportingBlobStorage) {
  3303. var xhr = new XMLHttpRequest(), blob;
  3304. xhr.open("GET", url, true);
  3305. xhr.responseType = "blob";
  3306. xhr.addEventListener("load", function () {
  3307. if (xhr.status === 200) {
  3308. // Blob as response (XHR2)
  3309. blob = xhr.response;
  3310. var transaction = _this.db.transaction(["textures"], "readwrite");
  3311. // the transaction could abort because of a QuotaExceededError error
  3312. transaction.onabort = function (event) {
  3313. try {
  3314. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3315. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3316. this.hasReachedQuota = true;
  3317. }
  3318. }
  3319. catch (ex) { }
  3320. generateBlobUrl();
  3321. };
  3322. transaction.oncomplete = function (event) {
  3323. generateBlobUrl();
  3324. };
  3325. var newTexture = { textureUrl: url, data: blob };
  3326. try {
  3327. // Put the blob into the dabase
  3328. var addRequest = transaction.objectStore("textures").put(newTexture);
  3329. addRequest.onsuccess = function (event) {
  3330. };
  3331. addRequest.onerror = function (event) {
  3332. generateBlobUrl();
  3333. };
  3334. }
  3335. catch (ex) {
  3336. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3337. if (ex.code === 25) {
  3338. Database.IsUASupportingBlobStorage = false;
  3339. }
  3340. image.src = url;
  3341. }
  3342. }
  3343. else {
  3344. image.src = url;
  3345. }
  3346. }, false);
  3347. xhr.addEventListener("error", function (event) {
  3348. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3349. image.src = url;
  3350. }, false);
  3351. xhr.send();
  3352. }
  3353. else {
  3354. image.src = url;
  3355. }
  3356. }
  3357. else {
  3358. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3359. image.src = url;
  3360. }
  3361. };
  3362. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3363. var _this = this;
  3364. var updateVersion = function (event) {
  3365. // the version is not yet in the DB or we need to update it
  3366. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3367. };
  3368. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3369. };
  3370. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3371. var _this = this;
  3372. if (this.isSupported) {
  3373. var version;
  3374. try {
  3375. var transaction = this.db.transaction(["versions"]);
  3376. transaction.oncomplete = function (event) {
  3377. if (version) {
  3378. // If the version in the JSON file is > than the version in DB
  3379. if (_this.manifestVersionFound > version.data) {
  3380. _this.mustUpdateRessources = true;
  3381. updateInDBCallback();
  3382. }
  3383. else {
  3384. callback(version.data);
  3385. }
  3386. }
  3387. else {
  3388. _this.mustUpdateRessources = true;
  3389. updateInDBCallback();
  3390. }
  3391. };
  3392. transaction.onabort = function (event) {
  3393. callback(-1);
  3394. };
  3395. var getRequest = transaction.objectStore("versions").get(url);
  3396. getRequest.onsuccess = function (event) {
  3397. version = (event.target).result;
  3398. };
  3399. getRequest.onerror = function (event) {
  3400. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3401. callback(-1);
  3402. };
  3403. }
  3404. catch (ex) {
  3405. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3406. callback(-1);
  3407. }
  3408. }
  3409. else {
  3410. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3411. callback(-1);
  3412. }
  3413. };
  3414. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3415. var _this = this;
  3416. if (this.isSupported && !this.hasReachedQuota) {
  3417. try {
  3418. // Open a transaction to the database
  3419. var transaction = this.db.transaction(["versions"], "readwrite");
  3420. // the transaction could abort because of a QuotaExceededError error
  3421. transaction.onabort = function (event) {
  3422. try {
  3423. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3424. _this.hasReachedQuota = true;
  3425. }
  3426. }
  3427. catch (ex) { }
  3428. callback(-1);
  3429. };
  3430. transaction.oncomplete = function (event) {
  3431. callback(_this.manifestVersionFound);
  3432. };
  3433. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3434. // Put the scene into the database
  3435. var addRequest = transaction.objectStore("versions").put(newVersion);
  3436. addRequest.onsuccess = function (event) {
  3437. };
  3438. addRequest.onerror = function (event) {
  3439. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3440. };
  3441. }
  3442. catch (ex) {
  3443. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3444. callback(-1);
  3445. }
  3446. }
  3447. else {
  3448. callback(-1);
  3449. }
  3450. };
  3451. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3452. var _this = this;
  3453. var completeUrl = Database.ReturnFullUrlLocation(url);
  3454. var saveAndLoadFile = function (event) {
  3455. // the scene is not yet in the DB, let's try to save it
  3456. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3457. };
  3458. this._checkVersionFromDB(completeUrl, function (version) {
  3459. if (version !== -1) {
  3460. if (!_this.mustUpdateRessources) {
  3461. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3462. }
  3463. else {
  3464. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3465. }
  3466. }
  3467. else {
  3468. errorCallback();
  3469. }
  3470. });
  3471. };
  3472. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3473. if (this.isSupported) {
  3474. var targetStore;
  3475. if (url.indexOf(".babylon") !== -1) {
  3476. targetStore = "scenes";
  3477. }
  3478. else {
  3479. targetStore = "textures";
  3480. }
  3481. var file;
  3482. var transaction = this.db.transaction([targetStore]);
  3483. transaction.oncomplete = function (event) {
  3484. if (file) {
  3485. callback(file.data);
  3486. }
  3487. else {
  3488. notInDBCallback();
  3489. }
  3490. };
  3491. transaction.onabort = function (event) {
  3492. notInDBCallback();
  3493. };
  3494. var getRequest = transaction.objectStore(targetStore).get(url);
  3495. getRequest.onsuccess = function (event) {
  3496. file = (event.target).result;
  3497. };
  3498. getRequest.onerror = function (event) {
  3499. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3500. notInDBCallback();
  3501. };
  3502. }
  3503. else {
  3504. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3505. callback();
  3506. }
  3507. };
  3508. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3509. var _this = this;
  3510. if (this.isSupported) {
  3511. var targetStore;
  3512. if (url.indexOf(".babylon") !== -1) {
  3513. targetStore = "scenes";
  3514. }
  3515. else {
  3516. targetStore = "textures";
  3517. }
  3518. // Create XHR
  3519. var xhr = new XMLHttpRequest(), fileData;
  3520. xhr.open("GET", url, true);
  3521. if (useArrayBuffer) {
  3522. xhr.responseType = "arraybuffer";
  3523. }
  3524. xhr.onprogress = progressCallback;
  3525. xhr.addEventListener("load", function () {
  3526. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3527. // Blob as response (XHR2)
  3528. //fileData = xhr.responseText;
  3529. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3530. if (!_this.hasReachedQuota) {
  3531. // Open a transaction to the database
  3532. var transaction = _this.db.transaction([targetStore], "readwrite");
  3533. // the transaction could abort because of a QuotaExceededError error
  3534. transaction.onabort = function (event) {
  3535. try {
  3536. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3537. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3538. this.hasReachedQuota = true;
  3539. }
  3540. }
  3541. catch (ex) { }
  3542. callback(fileData);
  3543. };
  3544. transaction.oncomplete = function (event) {
  3545. callback(fileData);
  3546. };
  3547. var newFile;
  3548. if (targetStore === "scenes") {
  3549. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3550. }
  3551. else {
  3552. newFile = { textureUrl: url, data: fileData };
  3553. }
  3554. try {
  3555. // Put the scene into the database
  3556. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3557. addRequest.onsuccess = function (event) {
  3558. };
  3559. addRequest.onerror = function (event) {
  3560. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3561. };
  3562. }
  3563. catch (ex) {
  3564. callback(fileData);
  3565. }
  3566. }
  3567. else {
  3568. callback(fileData);
  3569. }
  3570. }
  3571. else {
  3572. callback();
  3573. }
  3574. }, false);
  3575. xhr.addEventListener("error", function (event) {
  3576. BABYLON.Tools.Error("error on XHR request.");
  3577. callback();
  3578. }, false);
  3579. xhr.send();
  3580. }
  3581. else {
  3582. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3583. callback();
  3584. }
  3585. };
  3586. Database.IsUASupportingBlobStorage = true;
  3587. Database.IDBStorageEnabled = true;
  3588. Database.parseURL = function (url) {
  3589. var a = document.createElement('a');
  3590. a.href = url;
  3591. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3592. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3593. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3594. return absLocation;
  3595. };
  3596. Database.ReturnFullUrlLocation = function (url) {
  3597. if (url.indexOf("http:/") === -1) {
  3598. return (Database.parseURL(window.location.href) + url);
  3599. }
  3600. else {
  3601. return url;
  3602. }
  3603. };
  3604. return Database;
  3605. })();
  3606. BABYLON.Database = Database;
  3607. })(BABYLON || (BABYLON = {}));
  3608. var BABYLON;
  3609. (function (BABYLON) {
  3610. var Internals;
  3611. (function (Internals) {
  3612. /*
  3613. * Based on jsTGALoader - Javascript loader for TGA file
  3614. * By Vincent Thibault
  3615. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3616. */
  3617. var TGATools = (function () {
  3618. function TGATools() {
  3619. }
  3620. TGATools.GetTGAHeader = function (data) {
  3621. var offset = 0;
  3622. var header = {
  3623. id_length: data[offset++],
  3624. colormap_type: data[offset++],
  3625. image_type: data[offset++],
  3626. colormap_index: data[offset++] | data[offset++] << 8,
  3627. colormap_length: data[offset++] | data[offset++] << 8,
  3628. colormap_size: data[offset++],
  3629. origin: [
  3630. data[offset++] | data[offset++] << 8,
  3631. data[offset++] | data[offset++] << 8
  3632. ],
  3633. width: data[offset++] | data[offset++] << 8,
  3634. height: data[offset++] | data[offset++] << 8,
  3635. pixel_size: data[offset++],
  3636. flags: data[offset++]
  3637. };
  3638. return header;
  3639. };
  3640. TGATools.UploadContent = function (gl, data) {
  3641. // Not enough data to contain header ?
  3642. if (data.length < 19) {
  3643. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3644. return;
  3645. }
  3646. // Read Header
  3647. var offset = 18;
  3648. var header = TGATools.GetTGAHeader(data);
  3649. // Assume it's a valid Targa file.
  3650. if (header.id_length + offset > data.length) {
  3651. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3652. return;
  3653. }
  3654. // Skip not needed data
  3655. offset += header.id_length;
  3656. var use_rle = false;
  3657. var use_pal = false;
  3658. var use_rgb = false;
  3659. var use_grey = false;
  3660. // Get some informations.
  3661. switch (header.image_type) {
  3662. case TGATools._TYPE_RLE_INDEXED:
  3663. use_rle = true;
  3664. case TGATools._TYPE_INDEXED:
  3665. use_pal = true;
  3666. break;
  3667. case TGATools._TYPE_RLE_RGB:
  3668. use_rle = true;
  3669. case TGATools._TYPE_RGB:
  3670. use_rgb = true;
  3671. break;
  3672. case TGATools._TYPE_RLE_GREY:
  3673. use_rle = true;
  3674. case TGATools._TYPE_GREY:
  3675. use_grey = true;
  3676. break;
  3677. }
  3678. var pixel_data;
  3679. var numAlphaBits = header.flags & 0xf;
  3680. var pixel_size = header.pixel_size >> 3;
  3681. var pixel_total = header.width * header.height * pixel_size;
  3682. // Read palettes
  3683. var palettes;
  3684. if (use_pal) {
  3685. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3686. }
  3687. // Read LRE
  3688. if (use_rle) {
  3689. pixel_data = new Uint8Array(pixel_total);
  3690. var c, count, i;
  3691. var localOffset = 0;
  3692. var pixels = new Uint8Array(pixel_size);
  3693. while (offset < pixel_total && localOffset < pixel_total) {
  3694. c = data[offset++];
  3695. count = (c & 0x7f) + 1;
  3696. // RLE pixels
  3697. if (c & 0x80) {
  3698. // Bind pixel tmp array
  3699. for (i = 0; i < pixel_size; ++i) {
  3700. pixels[i] = data[offset++];
  3701. }
  3702. // Copy pixel array
  3703. for (i = 0; i < count; ++i) {
  3704. pixel_data.set(pixels, localOffset + i * pixel_size);
  3705. }
  3706. localOffset += pixel_size * count;
  3707. }
  3708. else {
  3709. count *= pixel_size;
  3710. for (i = 0; i < count; ++i) {
  3711. pixel_data[localOffset + i] = data[offset++];
  3712. }
  3713. localOffset += count;
  3714. }
  3715. }
  3716. }
  3717. else {
  3718. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3719. }
  3720. // Load to texture
  3721. var x_start, y_start, x_step, y_step, y_end, x_end;
  3722. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3723. default:
  3724. case TGATools._ORIGIN_UL:
  3725. x_start = 0;
  3726. x_step = 1;
  3727. x_end = header.width;
  3728. y_start = 0;
  3729. y_step = 1;
  3730. y_end = header.height;
  3731. break;
  3732. case TGATools._ORIGIN_BL:
  3733. x_start = 0;
  3734. x_step = 1;
  3735. x_end = header.width;
  3736. y_start = header.height - 1;
  3737. y_step = -1;
  3738. y_end = -1;
  3739. break;
  3740. case TGATools._ORIGIN_UR:
  3741. x_start = header.width - 1;
  3742. x_step = -1;
  3743. x_end = -1;
  3744. y_start = 0;
  3745. y_step = 1;
  3746. y_end = header.height;
  3747. break;
  3748. case TGATools._ORIGIN_BR:
  3749. x_start = header.width - 1;
  3750. x_step = -1;
  3751. x_end = -1;
  3752. y_start = header.height - 1;
  3753. y_step = -1;
  3754. y_end = -1;
  3755. break;
  3756. }
  3757. // Load the specify method
  3758. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3759. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3760. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3761. };
  3762. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3763. var image = pixel_data, colormap = palettes;
  3764. var width = header.width, height = header.height;
  3765. var color, i = 0, x, y;
  3766. var imageData = new Uint8Array(width * height * 4);
  3767. for (y = y_start; y !== y_end; y += y_step) {
  3768. for (x = x_start; x !== x_end; x += x_step, i++) {
  3769. color = image[i];
  3770. imageData[(x + width * y) * 4 + 3] = 255;
  3771. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3772. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3773. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3774. }
  3775. }
  3776. return imageData;
  3777. };
  3778. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3779. var image = pixel_data;
  3780. var width = header.width, height = header.height;
  3781. var color, i = 0, x, y;
  3782. var imageData = new Uint8Array(width * height * 4);
  3783. for (y = y_start; y !== y_end; y += y_step) {
  3784. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3785. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3786. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3787. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3788. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3789. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3790. }
  3791. }
  3792. return imageData;
  3793. };
  3794. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3795. var image = pixel_data;
  3796. var width = header.width, height = header.height;
  3797. var i = 0, x, y;
  3798. var imageData = new Uint8Array(width * height * 4);
  3799. for (y = y_start; y !== y_end; y += y_step) {
  3800. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3801. imageData[(x + width * y) * 4 + 3] = 255;
  3802. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3803. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3804. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3805. }
  3806. }
  3807. return imageData;
  3808. };
  3809. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3810. var image = pixel_data;
  3811. var width = header.width, height = header.height;
  3812. var i = 0, x, y;
  3813. var imageData = new Uint8Array(width * height * 4);
  3814. for (y = y_start; y !== y_end; y += y_step) {
  3815. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3816. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3817. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3818. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3819. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3820. }
  3821. }
  3822. return imageData;
  3823. };
  3824. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3825. var image = pixel_data;
  3826. var width = header.width, height = header.height;
  3827. var color, i = 0, x, y;
  3828. var imageData = new Uint8Array(width * height * 4);
  3829. for (y = y_start; y !== y_end; y += y_step) {
  3830. for (x = x_start; x !== x_end; x += x_step, i++) {
  3831. color = image[i];
  3832. imageData[(x + width * y) * 4 + 0] = color;
  3833. imageData[(x + width * y) * 4 + 1] = color;
  3834. imageData[(x + width * y) * 4 + 2] = color;
  3835. imageData[(x + width * y) * 4 + 3] = 255;
  3836. }
  3837. }
  3838. return imageData;
  3839. };
  3840. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3841. var image = pixel_data;
  3842. var width = header.width, height = header.height;
  3843. var i = 0, x, y;
  3844. var imageData = new Uint8Array(width * height * 4);
  3845. for (y = y_start; y !== y_end; y += y_step) {
  3846. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3847. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3848. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3849. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3850. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3851. }
  3852. }
  3853. return imageData;
  3854. };
  3855. TGATools._TYPE_NO_DATA = 0;
  3856. TGATools._TYPE_INDEXED = 1;
  3857. TGATools._TYPE_RGB = 2;
  3858. TGATools._TYPE_GREY = 3;
  3859. TGATools._TYPE_RLE_INDEXED = 9;
  3860. TGATools._TYPE_RLE_RGB = 10;
  3861. TGATools._TYPE_RLE_GREY = 11;
  3862. TGATools._ORIGIN_MASK = 0x30;
  3863. TGATools._ORIGIN_SHIFT = 0x04;
  3864. TGATools._ORIGIN_BL = 0x00;
  3865. TGATools._ORIGIN_BR = 0x01;
  3866. TGATools._ORIGIN_UL = 0x02;
  3867. TGATools._ORIGIN_UR = 0x03;
  3868. return TGATools;
  3869. })();
  3870. Internals.TGATools = TGATools;
  3871. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3872. })(BABYLON || (BABYLON = {}));
  3873. var BABYLON;
  3874. (function (BABYLON) {
  3875. var Internals;
  3876. (function (Internals) {
  3877. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3878. // All values and structures referenced from:
  3879. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3880. var DDS_MAGIC = 0x20534444;
  3881. 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;
  3882. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3883. 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;
  3884. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3885. function FourCCToInt32(value) {
  3886. return value.charCodeAt(0) +
  3887. (value.charCodeAt(1) << 8) +
  3888. (value.charCodeAt(2) << 16) +
  3889. (value.charCodeAt(3) << 24);
  3890. }
  3891. function Int32ToFourCC(value) {
  3892. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3893. }
  3894. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3895. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3896. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3897. var headerLengthInt = 31; // The header length in 32 bit ints
  3898. // Offsets into the header array
  3899. var off_magic = 0;
  3900. var off_size = 1;
  3901. var off_flags = 2;
  3902. var off_height = 3;
  3903. var off_width = 4;
  3904. var off_mipmapCount = 7;
  3905. var off_pfFlags = 20;
  3906. var off_pfFourCC = 21;
  3907. var off_RGBbpp = 22;
  3908. var off_RMask = 23;
  3909. var off_GMask = 24;
  3910. var off_BMask = 25;
  3911. var off_AMask = 26;
  3912. var off_caps1 = 27;
  3913. var off_caps2 = 28;
  3914. ;
  3915. var DDSTools = (function () {
  3916. function DDSTools() {
  3917. }
  3918. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3919. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3920. var mipmapCount = 1;
  3921. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3922. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3923. }
  3924. return {
  3925. width: header[off_width],
  3926. height: header[off_height],
  3927. mipmapCount: mipmapCount,
  3928. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3929. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3930. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3931. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3932. };
  3933. };
  3934. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3935. var byteArray = new Uint8Array(dataLength);
  3936. var srcData = new Uint8Array(arrayBuffer);
  3937. var index = 0;
  3938. for (var y = height - 1; y >= 0; y--) {
  3939. for (var x = 0; x < width; x++) {
  3940. var srcPos = dataOffset + (x + y * width) * 4;
  3941. byteArray[index + 2] = srcData[srcPos];
  3942. byteArray[index + 1] = srcData[srcPos + 1];
  3943. byteArray[index] = srcData[srcPos + 2];
  3944. byteArray[index + 3] = srcData[srcPos + 3];
  3945. index += 4;
  3946. }
  3947. }
  3948. return byteArray;
  3949. };
  3950. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3951. var byteArray = new Uint8Array(dataLength);
  3952. var srcData = new Uint8Array(arrayBuffer);
  3953. var index = 0;
  3954. for (var y = height - 1; y >= 0; y--) {
  3955. for (var x = 0; x < width; x++) {
  3956. var srcPos = dataOffset + (x + y * width) * 3;
  3957. byteArray[index + 2] = srcData[srcPos];
  3958. byteArray[index + 1] = srcData[srcPos + 1];
  3959. byteArray[index] = srcData[srcPos + 2];
  3960. index += 3;
  3961. }
  3962. }
  3963. return byteArray;
  3964. };
  3965. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3966. var byteArray = new Uint8Array(dataLength);
  3967. var srcData = new Uint8Array(arrayBuffer);
  3968. var index = 0;
  3969. for (var y = height - 1; y >= 0; y--) {
  3970. for (var x = 0; x < width; x++) {
  3971. var srcPos = dataOffset + (x + y * width);
  3972. byteArray[index] = srcData[srcPos];
  3973. index++;
  3974. }
  3975. }
  3976. return byteArray;
  3977. };
  3978. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3979. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3980. if (header[off_magic] != DDS_MAGIC) {
  3981. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3982. return;
  3983. }
  3984. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3985. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3986. return;
  3987. }
  3988. if (info.isFourCC) {
  3989. fourCC = header[off_pfFourCC];
  3990. switch (fourCC) {
  3991. case FOURCC_DXT1:
  3992. blockBytes = 8;
  3993. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3994. break;
  3995. case FOURCC_DXT3:
  3996. blockBytes = 16;
  3997. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3998. break;
  3999. case FOURCC_DXT5:
  4000. blockBytes = 16;
  4001. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4002. break;
  4003. default:
  4004. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4005. return;
  4006. }
  4007. }
  4008. mipmapCount = 1;
  4009. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4010. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4011. }
  4012. var bpp = header[off_RGBbpp];
  4013. for (var face = 0; face < faces; face++) {
  4014. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4015. width = header[off_width];
  4016. height = header[off_height];
  4017. dataOffset = header[off_size] + 4;
  4018. for (i = 0; i < mipmapCount; ++i) {
  4019. if (info.isRGB) {
  4020. if (bpp == 24) {
  4021. dataLength = width * height * 3;
  4022. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4023. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4024. }
  4025. else {
  4026. dataLength = width * height * 4;
  4027. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4028. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4029. }
  4030. }
  4031. else if (info.isLuminance) {
  4032. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4033. var unpaddedRowSize = width;
  4034. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4035. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4036. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4037. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4038. }
  4039. else {
  4040. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4041. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4042. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4043. }
  4044. dataOffset += dataLength;
  4045. width *= 0.5;
  4046. height *= 0.5;
  4047. width = Math.max(1.0, width);
  4048. height = Math.max(1.0, height);
  4049. }
  4050. }
  4051. };
  4052. return DDSTools;
  4053. })();
  4054. Internals.DDSTools = DDSTools;
  4055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4056. })(BABYLON || (BABYLON = {}));
  4057. var BABYLON;
  4058. (function (BABYLON) {
  4059. var SmartArray = (function () {
  4060. function SmartArray(capacity) {
  4061. this.length = 0;
  4062. this._duplicateId = 0;
  4063. this.data = new Array(capacity);
  4064. this._id = SmartArray._GlobalId++;
  4065. }
  4066. SmartArray.prototype.push = function (value) {
  4067. this.data[this.length++] = value;
  4068. if (this.length > this.data.length) {
  4069. this.data.length *= 2;
  4070. }
  4071. if (!value.__smartArrayFlags) {
  4072. value.__smartArrayFlags = {};
  4073. }
  4074. value.__smartArrayFlags[this._id] = this._duplicateId;
  4075. };
  4076. SmartArray.prototype.pushNoDuplicate = function (value) {
  4077. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4078. return;
  4079. }
  4080. this.push(value);
  4081. };
  4082. SmartArray.prototype.sort = function (compareFn) {
  4083. this.data.sort(compareFn);
  4084. };
  4085. SmartArray.prototype.reset = function () {
  4086. this.length = 0;
  4087. this._duplicateId++;
  4088. };
  4089. SmartArray.prototype.concat = function (array) {
  4090. if (array.length === 0) {
  4091. return;
  4092. }
  4093. if (this.length + array.length > this.data.length) {
  4094. this.data.length = (this.length + array.length) * 2;
  4095. }
  4096. for (var index = 0; index < array.length; index++) {
  4097. this.data[this.length++] = (array.data || array)[index];
  4098. }
  4099. };
  4100. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4101. if (array.length === 0) {
  4102. return;
  4103. }
  4104. if (this.length + array.length > this.data.length) {
  4105. this.data.length = (this.length + array.length) * 2;
  4106. }
  4107. for (var index = 0; index < array.length; index++) {
  4108. var item = (array.data || array)[index];
  4109. this.pushNoDuplicate(item);
  4110. }
  4111. };
  4112. SmartArray.prototype.indexOf = function (value) {
  4113. var position = this.data.indexOf(value);
  4114. if (position >= this.length) {
  4115. return -1;
  4116. }
  4117. return position;
  4118. };
  4119. // Statics
  4120. SmartArray._GlobalId = 0;
  4121. return SmartArray;
  4122. })();
  4123. BABYLON.SmartArray = SmartArray;
  4124. })(BABYLON || (BABYLON = {}));
  4125. var BABYLON;
  4126. (function (BABYLON) {
  4127. var SmartCollection = (function () {
  4128. function SmartCollection(capacity) {
  4129. if (capacity === void 0) { capacity = 10; }
  4130. this.count = 0;
  4131. this._initialCapacity = capacity;
  4132. this.items = {};
  4133. this._keys = new Array(this._initialCapacity);
  4134. }
  4135. SmartCollection.prototype.add = function (key, item) {
  4136. if (this.items[key] != undefined) {
  4137. return -1;
  4138. }
  4139. this.items[key] = item;
  4140. //literal keys are always strings, but we keep source type of key in _keys array
  4141. this._keys[this.count++] = key;
  4142. if (this.count > this._keys.length) {
  4143. this._keys.length *= 2;
  4144. }
  4145. return this.count;
  4146. };
  4147. SmartCollection.prototype.remove = function (key) {
  4148. if (this.items[key] == undefined) {
  4149. return -1;
  4150. }
  4151. return this.removeItemOfIndex(this.indexOf(key));
  4152. };
  4153. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4154. if (index < this.count && index > -1) {
  4155. delete this.items[this._keys[index]];
  4156. //here, shifting by hand is better optimised than .splice
  4157. while (index < this.count) {
  4158. this._keys[index] = this._keys[index + 1];
  4159. index++;
  4160. }
  4161. }
  4162. else {
  4163. return -1;
  4164. }
  4165. return --this.count;
  4166. };
  4167. SmartCollection.prototype.indexOf = function (key) {
  4168. for (var i = 0; i !== this.count; i++) {
  4169. if (this._keys[i] === key) {
  4170. return i;
  4171. }
  4172. }
  4173. return -1;
  4174. };
  4175. SmartCollection.prototype.item = function (key) {
  4176. return this.items[key];
  4177. };
  4178. SmartCollection.prototype.getAllKeys = function () {
  4179. if (this.count > 0) {
  4180. var keys = new Array(this.count);
  4181. for (var i = 0; i < this.count; i++) {
  4182. keys[i] = this._keys[i];
  4183. }
  4184. return keys;
  4185. }
  4186. else {
  4187. return undefined;
  4188. }
  4189. };
  4190. SmartCollection.prototype.getKeyByIndex = function (index) {
  4191. if (index < this.count && index > -1) {
  4192. return this._keys[index];
  4193. }
  4194. else {
  4195. return undefined;
  4196. }
  4197. };
  4198. SmartCollection.prototype.getItemByIndex = function (index) {
  4199. if (index < this.count && index > -1) {
  4200. return this.items[this._keys[index]];
  4201. }
  4202. else {
  4203. return undefined;
  4204. }
  4205. };
  4206. SmartCollection.prototype.empty = function () {
  4207. if (this.count > 0) {
  4208. this.count = 0;
  4209. this.items = {};
  4210. this._keys = new Array(this._initialCapacity);
  4211. }
  4212. };
  4213. SmartCollection.prototype.forEach = function (block) {
  4214. var key;
  4215. for (key in this.items) {
  4216. if (this.items.hasOwnProperty(key)) {
  4217. block(this.items[key]);
  4218. }
  4219. }
  4220. };
  4221. return SmartCollection;
  4222. })();
  4223. BABYLON.SmartCollection = SmartCollection;
  4224. })(BABYLON || (BABYLON = {}));
  4225. var BABYLON;
  4226. (function (BABYLON) {
  4227. // Screenshots
  4228. var screenshotCanvas;
  4229. var cloneValue = function (source, destinationObject) {
  4230. if (!source)
  4231. return null;
  4232. if (source instanceof BABYLON.Mesh) {
  4233. return null;
  4234. }
  4235. if (source instanceof BABYLON.SubMesh) {
  4236. return source.clone(destinationObject);
  4237. }
  4238. else if (source.clone) {
  4239. return source.clone();
  4240. }
  4241. return null;
  4242. };
  4243. var Tools = (function () {
  4244. function Tools() {
  4245. }
  4246. Tools.ToHex = function (i) {
  4247. var str = i.toString(16);
  4248. if (i <= 15) {
  4249. return ("0" + str).toUpperCase();
  4250. }
  4251. return str.toUpperCase();
  4252. };
  4253. Tools.SetImmediate = function (action) {
  4254. if (window.setImmediate) {
  4255. window.setImmediate(action);
  4256. }
  4257. else {
  4258. setTimeout(action, 1);
  4259. }
  4260. };
  4261. Tools.IsExponantOfTwo = function (value) {
  4262. var count = 1;
  4263. do {
  4264. count *= 2;
  4265. } while (count < value);
  4266. return count === value;
  4267. };
  4268. Tools.GetExponantOfTwo = function (value, max) {
  4269. var count = 1;
  4270. do {
  4271. count *= 2;
  4272. } while (count < value);
  4273. if (count > max)
  4274. count = max;
  4275. return count;
  4276. };
  4277. Tools.GetFilename = function (path) {
  4278. var index = path.lastIndexOf("/");
  4279. if (index < 0)
  4280. return path;
  4281. return path.substring(index + 1);
  4282. };
  4283. Tools.GetDOMTextContent = function (element) {
  4284. var result = "";
  4285. var child = element.firstChild;
  4286. while (child) {
  4287. if (child.nodeType === 3) {
  4288. result += child.textContent;
  4289. }
  4290. child = child.nextSibling;
  4291. }
  4292. return result;
  4293. };
  4294. Tools.ToDegrees = function (angle) {
  4295. return angle * 180 / Math.PI;
  4296. };
  4297. Tools.ToRadians = function (angle) {
  4298. return angle * Math.PI / 180;
  4299. };
  4300. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4301. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4302. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4303. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4304. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4305. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4306. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4307. }
  4308. return {
  4309. minimum: minimum,
  4310. maximum: maximum
  4311. };
  4312. };
  4313. Tools.ExtractMinAndMax = function (positions, start, count) {
  4314. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4315. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4316. for (var index = start; index < start + count; index++) {
  4317. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4318. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4319. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4320. }
  4321. return {
  4322. minimum: minimum,
  4323. maximum: maximum
  4324. };
  4325. };
  4326. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4327. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4328. return undefined;
  4329. return Array.isArray(obj) ? obj : [obj];
  4330. };
  4331. // Misc.
  4332. Tools.GetPointerPrefix = function () {
  4333. var eventPrefix = "pointer";
  4334. // Check if hand.js is referenced or if the browser natively supports pointer events
  4335. if (!navigator.pointerEnabled) {
  4336. eventPrefix = "mouse";
  4337. }
  4338. return eventPrefix;
  4339. };
  4340. Tools.QueueNewFrame = function (func) {
  4341. if (window.requestAnimationFrame)
  4342. window.requestAnimationFrame(func);
  4343. else if (window.msRequestAnimationFrame)
  4344. window.msRequestAnimationFrame(func);
  4345. else if (window.webkitRequestAnimationFrame)
  4346. window.webkitRequestAnimationFrame(func);
  4347. else if (window.mozRequestAnimationFrame)
  4348. window.mozRequestAnimationFrame(func);
  4349. else if (window.oRequestAnimationFrame)
  4350. window.oRequestAnimationFrame(func);
  4351. else {
  4352. window.setTimeout(func, 16);
  4353. }
  4354. };
  4355. Tools.RequestFullscreen = function (element) {
  4356. if (element.requestFullscreen)
  4357. element.requestFullscreen();
  4358. else if (element.msRequestFullscreen)
  4359. element.msRequestFullscreen();
  4360. else if (element.webkitRequestFullscreen)
  4361. element.webkitRequestFullscreen();
  4362. else if (element.mozRequestFullScreen)
  4363. element.mozRequestFullScreen();
  4364. };
  4365. Tools.ExitFullscreen = function () {
  4366. if (document.exitFullscreen) {
  4367. document.exitFullscreen();
  4368. }
  4369. else if (document.mozCancelFullScreen) {
  4370. document.mozCancelFullScreen();
  4371. }
  4372. else if (document.webkitCancelFullScreen) {
  4373. document.webkitCancelFullScreen();
  4374. }
  4375. else if (document.msCancelFullScreen) {
  4376. document.msCancelFullScreen();
  4377. }
  4378. };
  4379. // External files
  4380. Tools.CleanUrl = function (url) {
  4381. url = url.replace(/#/mg, "%23");
  4382. return url;
  4383. };
  4384. Tools.LoadImage = function (url, onload, onerror, database) {
  4385. url = Tools.CleanUrl(url);
  4386. var img = new Image();
  4387. if (url.substr(0, 5) !== "data:")
  4388. img.crossOrigin = 'anonymous';
  4389. img.onload = function () {
  4390. onload(img);
  4391. };
  4392. img.onerror = function (err) {
  4393. Tools.Error("Error while trying to load texture: " + url);
  4394. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4395. onload(img);
  4396. };
  4397. var noIndexedDB = function () {
  4398. img.src = url;
  4399. };
  4400. var loadFromIndexedDB = function () {
  4401. database.loadImageFromDB(url, img);
  4402. };
  4403. //ANY database to do!
  4404. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4405. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4406. }
  4407. else {
  4408. if (url.indexOf("file:") === -1) {
  4409. noIndexedDB();
  4410. }
  4411. else {
  4412. try {
  4413. var textureName = url.substring(5);
  4414. var blobURL;
  4415. try {
  4416. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4417. }
  4418. catch (ex) {
  4419. // Chrome doesn't support oneTimeOnly parameter
  4420. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4421. }
  4422. img.src = blobURL;
  4423. }
  4424. catch (e) {
  4425. img.src = null;
  4426. }
  4427. }
  4428. }
  4429. return img;
  4430. };
  4431. //ANY
  4432. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4433. url = Tools.CleanUrl(url);
  4434. var noIndexedDB = function () {
  4435. var request = new XMLHttpRequest();
  4436. var loadUrl = Tools.BaseUrl + url;
  4437. request.open('GET', loadUrl, true);
  4438. if (useArrayBuffer) {
  4439. request.responseType = "arraybuffer";
  4440. }
  4441. request.onprogress = progressCallBack;
  4442. request.onreadystatechange = function () {
  4443. if (request.readyState === 4) {
  4444. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4445. callback(!useArrayBuffer ? request.responseText : request.response);
  4446. }
  4447. else {
  4448. if (onError) {
  4449. onError();
  4450. }
  4451. else {
  4452. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4453. }
  4454. }
  4455. }
  4456. };
  4457. request.send(null);
  4458. };
  4459. var loadFromIndexedDB = function () {
  4460. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4461. };
  4462. if (url.indexOf("file:") !== -1) {
  4463. var fileName = url.substring(5);
  4464. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4465. }
  4466. else {
  4467. // Caching all files
  4468. if (database && database.enableSceneOffline) {
  4469. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4470. }
  4471. else {
  4472. noIndexedDB();
  4473. }
  4474. }
  4475. };
  4476. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4477. var reader = new FileReader();
  4478. reader.onload = function (e) {
  4479. //target doesn't have result from ts 1.3
  4480. callback(e.target['result']);
  4481. };
  4482. reader.onprogress = progressCallback;
  4483. reader.readAsDataURL(fileToLoad);
  4484. };
  4485. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4486. var reader = new FileReader();
  4487. reader.onerror = function (e) {
  4488. Tools.Log("Error while reading file: " + fileToLoad.name);
  4489. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4490. };
  4491. reader.onload = function (e) {
  4492. //target doesn't have result from ts 1.3
  4493. callback(e.target['result']);
  4494. };
  4495. reader.onprogress = progressCallBack;
  4496. if (!useArrayBuffer) {
  4497. // Asynchronous read
  4498. reader.readAsText(fileToLoad);
  4499. }
  4500. else {
  4501. reader.readAsArrayBuffer(fileToLoad);
  4502. }
  4503. };
  4504. // Misc.
  4505. Tools.Clamp = function (value, min, max) {
  4506. if (min === void 0) { min = 0; }
  4507. if (max === void 0) { max = 1; }
  4508. return Math.min(max, Math.max(min, value));
  4509. };
  4510. // Returns -1 when value is a negative number and
  4511. // +1 when value is a positive number.
  4512. Tools.Sign = function (value) {
  4513. value = +value; // convert to a number
  4514. if (value === 0 || isNaN(value))
  4515. return value;
  4516. return value > 0 ? 1 : -1;
  4517. };
  4518. Tools.Format = function (value, decimals) {
  4519. if (decimals === void 0) { decimals = 2; }
  4520. return value.toFixed(decimals);
  4521. };
  4522. Tools.CheckExtends = function (v, min, max) {
  4523. if (v.x < min.x)
  4524. min.x = v.x;
  4525. if (v.y < min.y)
  4526. min.y = v.y;
  4527. if (v.z < min.z)
  4528. min.z = v.z;
  4529. if (v.x > max.x)
  4530. max.x = v.x;
  4531. if (v.y > max.y)
  4532. max.y = v.y;
  4533. if (v.z > max.z)
  4534. max.z = v.z;
  4535. };
  4536. Tools.WithinEpsilon = function (a, b, epsilon) {
  4537. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4538. var num = a - b;
  4539. return -epsilon <= num && num <= epsilon;
  4540. };
  4541. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4542. for (var prop in source) {
  4543. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4544. continue;
  4545. }
  4546. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4547. continue;
  4548. }
  4549. var sourceValue = source[prop];
  4550. var typeOfSourceValue = typeof sourceValue;
  4551. if (typeOfSourceValue === "function") {
  4552. continue;
  4553. }
  4554. if (typeOfSourceValue === "object") {
  4555. if (sourceValue instanceof Array) {
  4556. destination[prop] = [];
  4557. if (sourceValue.length > 0) {
  4558. if (typeof sourceValue[0] == "object") {
  4559. for (var index = 0; index < sourceValue.length; index++) {
  4560. var clonedValue = cloneValue(sourceValue[index], destination);
  4561. if (destination[prop].indexOf(clonedValue) === -1) {
  4562. destination[prop].push(clonedValue);
  4563. }
  4564. }
  4565. }
  4566. else {
  4567. destination[prop] = sourceValue.slice(0);
  4568. }
  4569. }
  4570. }
  4571. else {
  4572. destination[prop] = cloneValue(sourceValue, destination);
  4573. }
  4574. }
  4575. else {
  4576. destination[prop] = sourceValue;
  4577. }
  4578. }
  4579. };
  4580. Tools.IsEmpty = function (obj) {
  4581. for (var i in obj) {
  4582. return false;
  4583. }
  4584. return true;
  4585. };
  4586. Tools.RegisterTopRootEvents = function (events) {
  4587. for (var index = 0; index < events.length; index++) {
  4588. var event = events[index];
  4589. window.addEventListener(event.name, event.handler, false);
  4590. try {
  4591. if (window.parent) {
  4592. window.parent.addEventListener(event.name, event.handler, false);
  4593. }
  4594. }
  4595. catch (e) {
  4596. }
  4597. }
  4598. };
  4599. Tools.UnregisterTopRootEvents = function (events) {
  4600. for (var index = 0; index < events.length; index++) {
  4601. var event = events[index];
  4602. window.removeEventListener(event.name, event.handler);
  4603. try {
  4604. if (window.parent) {
  4605. window.parent.removeEventListener(event.name, event.handler);
  4606. }
  4607. }
  4608. catch (e) {
  4609. }
  4610. }
  4611. };
  4612. Tools.DumpFramebuffer = function (width, height, engine) {
  4613. // Read the contents of the framebuffer
  4614. var numberOfChannelsByLine = width * 4;
  4615. var halfHeight = height / 2;
  4616. //Reading datas from WebGL
  4617. var data = engine.readPixels(0, 0, width, height);
  4618. //To flip image on Y axis.
  4619. for (var i = 0; i < halfHeight; i++) {
  4620. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4621. var currentCell = j + i * numberOfChannelsByLine;
  4622. var targetLine = height - i - 1;
  4623. var targetCell = j + targetLine * numberOfChannelsByLine;
  4624. var temp = data[currentCell];
  4625. data[currentCell] = data[targetCell];
  4626. data[targetCell] = temp;
  4627. }
  4628. }
  4629. // Create a 2D canvas to store the result
  4630. if (!screenshotCanvas) {
  4631. screenshotCanvas = document.createElement('canvas');
  4632. }
  4633. screenshotCanvas.width = width;
  4634. screenshotCanvas.height = height;
  4635. var context = screenshotCanvas.getContext('2d');
  4636. // Copy the pixels to a 2D canvas
  4637. var imageData = context.createImageData(width, height);
  4638. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4639. var castData = imageData.data;
  4640. castData.set(data);
  4641. context.putImageData(imageData, 0, 0);
  4642. var base64Image = screenshotCanvas.toDataURL();
  4643. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4644. if (("download" in document.createElement("a"))) {
  4645. var a = window.document.createElement("a");
  4646. a.href = base64Image;
  4647. var date = new Date();
  4648. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4649. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4650. window.document.body.appendChild(a);
  4651. a.addEventListener("click", function () {
  4652. a.parentElement.removeChild(a);
  4653. });
  4654. a.click();
  4655. }
  4656. else {
  4657. var newWindow = window.open("");
  4658. var img = newWindow.document.createElement("img");
  4659. img.src = base64Image;
  4660. newWindow.document.body.appendChild(img);
  4661. }
  4662. };
  4663. Tools.CreateScreenshot = function (engine, camera, size) {
  4664. var width;
  4665. var height;
  4666. var scene = camera.getScene();
  4667. var previousCamera = null;
  4668. if (scene.activeCamera !== camera) {
  4669. previousCamera = scene.activeCamera;
  4670. scene.activeCamera = camera;
  4671. }
  4672. //If a precision value is specified
  4673. if (size.precision) {
  4674. width = Math.round(engine.getRenderWidth() * size.precision);
  4675. height = Math.round(width / engine.getAspectRatio(camera));
  4676. size = { width: width, height: height };
  4677. }
  4678. else if (size.width && size.height) {
  4679. width = size.width;
  4680. height = size.height;
  4681. }
  4682. else if (size.width && !size.height) {
  4683. width = size.width;
  4684. height = Math.round(width / engine.getAspectRatio(camera));
  4685. size = { width: width, height: height };
  4686. }
  4687. else if (size.height && !size.width) {
  4688. height = size.height;
  4689. width = Math.round(height * engine.getAspectRatio(camera));
  4690. size = { width: width, height: height };
  4691. }
  4692. else if (!isNaN(size)) {
  4693. height = size;
  4694. width = size;
  4695. }
  4696. else {
  4697. Tools.Error("Invalid 'size' parameter !");
  4698. return;
  4699. }
  4700. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4701. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4702. texture.renderList = scene.meshes;
  4703. texture.onAfterRender = function () {
  4704. Tools.DumpFramebuffer(width, height, engine);
  4705. };
  4706. scene.incrementRenderId();
  4707. texture.render(true);
  4708. texture.dispose();
  4709. if (previousCamera) {
  4710. scene.activeCamera = previousCamera;
  4711. }
  4712. };
  4713. // XHR response validator for local file scenario
  4714. Tools.ValidateXHRData = function (xhr, dataType) {
  4715. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4716. if (dataType === void 0) { dataType = 7; }
  4717. try {
  4718. if (dataType & 1) {
  4719. if (xhr.responseText && xhr.responseText.length > 0) {
  4720. return true;
  4721. }
  4722. else if (dataType === 1) {
  4723. return false;
  4724. }
  4725. }
  4726. if (dataType & 2) {
  4727. // Check header width and height since there is no "TGA" magic number
  4728. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4729. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4730. return true;
  4731. }
  4732. else if (dataType === 2) {
  4733. return false;
  4734. }
  4735. }
  4736. if (dataType & 4) {
  4737. // Check for the "DDS" magic number
  4738. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4739. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4740. return true;
  4741. }
  4742. else {
  4743. return false;
  4744. }
  4745. }
  4746. }
  4747. catch (e) {
  4748. }
  4749. return false;
  4750. };
  4751. Object.defineProperty(Tools, "NoneLogLevel", {
  4752. get: function () {
  4753. return Tools._NoneLogLevel;
  4754. },
  4755. enumerable: true,
  4756. configurable: true
  4757. });
  4758. Object.defineProperty(Tools, "MessageLogLevel", {
  4759. get: function () {
  4760. return Tools._MessageLogLevel;
  4761. },
  4762. enumerable: true,
  4763. configurable: true
  4764. });
  4765. Object.defineProperty(Tools, "WarningLogLevel", {
  4766. get: function () {
  4767. return Tools._WarningLogLevel;
  4768. },
  4769. enumerable: true,
  4770. configurable: true
  4771. });
  4772. Object.defineProperty(Tools, "ErrorLogLevel", {
  4773. get: function () {
  4774. return Tools._ErrorLogLevel;
  4775. },
  4776. enumerable: true,
  4777. configurable: true
  4778. });
  4779. Object.defineProperty(Tools, "AllLogLevel", {
  4780. get: function () {
  4781. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Tools._AddLogEntry = function (entry) {
  4787. Tools._LogCache = entry + Tools._LogCache;
  4788. if (Tools.OnNewCacheEntry) {
  4789. Tools.OnNewCacheEntry(entry);
  4790. }
  4791. };
  4792. Tools._FormatMessage = function (message) {
  4793. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4794. var date = new Date();
  4795. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4796. };
  4797. Tools._LogDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._LogEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.log("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._WarnDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._WarnEnabled = function (message) {
  4810. var formattedMessage = Tools._FormatMessage(message);
  4811. console.warn("BJS - " + formattedMessage);
  4812. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4813. Tools._AddLogEntry(entry);
  4814. };
  4815. Tools._ErrorDisabled = function (message) {
  4816. // nothing to do
  4817. };
  4818. Tools._ErrorEnabled = function (message) {
  4819. Tools.errorsCount++;
  4820. var formattedMessage = Tools._FormatMessage(message);
  4821. console.error("BJS - " + formattedMessage);
  4822. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4823. Tools._AddLogEntry(entry);
  4824. };
  4825. Object.defineProperty(Tools, "LogCache", {
  4826. get: function () {
  4827. return Tools._LogCache;
  4828. },
  4829. enumerable: true,
  4830. configurable: true
  4831. });
  4832. Tools.ClearLogCache = function () {
  4833. Tools._LogCache = "";
  4834. Tools.errorsCount = 0;
  4835. };
  4836. Object.defineProperty(Tools, "LogLevels", {
  4837. set: function (level) {
  4838. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4839. Tools.Log = Tools._LogEnabled;
  4840. }
  4841. else {
  4842. Tools.Log = Tools._LogDisabled;
  4843. }
  4844. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4845. Tools.Warn = Tools._WarnEnabled;
  4846. }
  4847. else {
  4848. Tools.Warn = Tools._WarnDisabled;
  4849. }
  4850. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4851. Tools.Error = Tools._ErrorEnabled;
  4852. }
  4853. else {
  4854. Tools.Error = Tools._ErrorDisabled;
  4855. }
  4856. },
  4857. enumerable: true,
  4858. configurable: true
  4859. });
  4860. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4861. get: function () {
  4862. return Tools._PerformanceNoneLogLevel;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4868. get: function () {
  4869. return Tools._PerformanceUserMarkLogLevel;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4875. get: function () {
  4876. return Tools._PerformanceConsoleLogLevel;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4882. set: function (level) {
  4883. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4884. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4885. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4886. return;
  4887. }
  4888. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4889. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4890. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4891. return;
  4892. }
  4893. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4894. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4895. },
  4896. enumerable: true,
  4897. configurable: true
  4898. });
  4899. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4900. };
  4901. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4902. };
  4903. Tools._StartUserMark = function (counterName, condition) {
  4904. if (condition === void 0) { condition = true; }
  4905. if (!condition || !Tools._performance.mark) {
  4906. return;
  4907. }
  4908. Tools._performance.mark(counterName + "-Begin");
  4909. };
  4910. Tools._EndUserMark = function (counterName, condition) {
  4911. if (condition === void 0) { condition = true; }
  4912. if (!condition || !Tools._performance.mark) {
  4913. return;
  4914. }
  4915. Tools._performance.mark(counterName + "-End");
  4916. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4917. };
  4918. Tools._StartPerformanceConsole = function (counterName, condition) {
  4919. if (condition === void 0) { condition = true; }
  4920. if (!condition) {
  4921. return;
  4922. }
  4923. Tools._StartUserMark(counterName, condition);
  4924. if (console.time) {
  4925. console.time(counterName);
  4926. }
  4927. };
  4928. Tools._EndPerformanceConsole = function (counterName, condition) {
  4929. if (condition === void 0) { condition = true; }
  4930. if (!condition) {
  4931. return;
  4932. }
  4933. Tools._EndUserMark(counterName, condition);
  4934. if (console.time) {
  4935. console.timeEnd(counterName);
  4936. }
  4937. };
  4938. Object.defineProperty(Tools, "Now", {
  4939. get: function () {
  4940. if (window.performance && window.performance.now) {
  4941. return window.performance.now();
  4942. }
  4943. return new Date().getTime();
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. // Deprecated
  4949. Tools.GetFps = function () {
  4950. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4951. return 0;
  4952. };
  4953. Tools.BaseUrl = "";
  4954. // Logs
  4955. Tools._NoneLogLevel = 0;
  4956. Tools._MessageLogLevel = 1;
  4957. Tools._WarningLogLevel = 2;
  4958. Tools._ErrorLogLevel = 4;
  4959. Tools._LogCache = "";
  4960. Tools.errorsCount = 0;
  4961. Tools.Log = Tools._LogEnabled;
  4962. Tools.Warn = Tools._WarnEnabled;
  4963. Tools.Error = Tools._ErrorEnabled;
  4964. // Performances
  4965. Tools._PerformanceNoneLogLevel = 0;
  4966. Tools._PerformanceUserMarkLogLevel = 1;
  4967. Tools._PerformanceConsoleLogLevel = 2;
  4968. Tools._performance = window.performance;
  4969. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4970. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4971. return Tools;
  4972. })();
  4973. BABYLON.Tools = Tools;
  4974. /**
  4975. * An implementation of a loop for asynchronous functions.
  4976. */
  4977. var AsyncLoop = (function () {
  4978. /**
  4979. * Constroctor.
  4980. * @param iterations the number of iterations.
  4981. * @param _fn the function to run each iteration
  4982. * @param _successCallback the callback that will be called upon succesful execution
  4983. * @param offset starting offset.
  4984. */
  4985. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4986. if (offset === void 0) { offset = 0; }
  4987. this.iterations = iterations;
  4988. this._fn = _fn;
  4989. this._successCallback = _successCallback;
  4990. this.index = offset - 1;
  4991. this._done = false;
  4992. }
  4993. /**
  4994. * Execute the next iteration. Must be called after the last iteration was finished.
  4995. */
  4996. AsyncLoop.prototype.executeNext = function () {
  4997. if (!this._done) {
  4998. if (this.index + 1 < this.iterations) {
  4999. ++this.index;
  5000. this._fn(this);
  5001. }
  5002. else {
  5003. this.breakLoop();
  5004. }
  5005. }
  5006. };
  5007. /**
  5008. * Break the loop and run the success callback.
  5009. */
  5010. AsyncLoop.prototype.breakLoop = function () {
  5011. this._done = true;
  5012. this._successCallback();
  5013. };
  5014. /**
  5015. * Helper function
  5016. */
  5017. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5018. if (offset === void 0) { offset = 0; }
  5019. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5020. loop.executeNext();
  5021. return loop;
  5022. };
  5023. /**
  5024. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5025. * @param iterations total number of iterations
  5026. * @param syncedIterations number of synchronous iterations in each async iteration.
  5027. * @param fn the function to call each iteration.
  5028. * @param callback a success call back that will be called when iterating stops.
  5029. * @param breakFunction a break condition (optional)
  5030. * @param timeout timeout settings for the setTimeout function. default - 0.
  5031. * @constructor
  5032. */
  5033. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5034. if (timeout === void 0) { timeout = 0; }
  5035. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5036. if (breakFunction && breakFunction())
  5037. loop.breakLoop();
  5038. else {
  5039. setTimeout(function () {
  5040. for (var i = 0; i < syncedIterations; ++i) {
  5041. var iteration = (loop.index * syncedIterations) + i;
  5042. if (iteration >= iterations)
  5043. break;
  5044. fn(iteration);
  5045. if (breakFunction && breakFunction()) {
  5046. loop.breakLoop();
  5047. break;
  5048. }
  5049. }
  5050. loop.executeNext();
  5051. }, timeout);
  5052. }
  5053. }, callback);
  5054. };
  5055. return AsyncLoop;
  5056. })();
  5057. BABYLON.AsyncLoop = AsyncLoop;
  5058. })(BABYLON || (BABYLON = {}));
  5059. var BABYLON;
  5060. (function (BABYLON) {
  5061. var _DepthCullingState = (function () {
  5062. function _DepthCullingState() {
  5063. this._isDepthTestDirty = false;
  5064. this._isDepthMaskDirty = false;
  5065. this._isDepthFuncDirty = false;
  5066. this._isCullFaceDirty = false;
  5067. this._isCullDirty = false;
  5068. this._isZOffsetDirty = false;
  5069. }
  5070. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5071. get: function () {
  5072. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5073. },
  5074. enumerable: true,
  5075. configurable: true
  5076. });
  5077. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5078. get: function () {
  5079. return this._zOffset;
  5080. },
  5081. set: function (value) {
  5082. if (this._zOffset === value) {
  5083. return;
  5084. }
  5085. this._zOffset = value;
  5086. this._isZOffsetDirty = true;
  5087. },
  5088. enumerable: true,
  5089. configurable: true
  5090. });
  5091. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5092. get: function () {
  5093. return this._cullFace;
  5094. },
  5095. set: function (value) {
  5096. if (this._cullFace === value) {
  5097. return;
  5098. }
  5099. this._cullFace = value;
  5100. this._isCullFaceDirty = true;
  5101. },
  5102. enumerable: true,
  5103. configurable: true
  5104. });
  5105. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5106. get: function () {
  5107. return this._cull;
  5108. },
  5109. set: function (value) {
  5110. if (this._cull === value) {
  5111. return;
  5112. }
  5113. this._cull = value;
  5114. this._isCullDirty = true;
  5115. },
  5116. enumerable: true,
  5117. configurable: true
  5118. });
  5119. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5120. get: function () {
  5121. return this._depthFunc;
  5122. },
  5123. set: function (value) {
  5124. if (this._depthFunc === value) {
  5125. return;
  5126. }
  5127. this._depthFunc = value;
  5128. this._isDepthFuncDirty = true;
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5134. get: function () {
  5135. return this._depthMask;
  5136. },
  5137. set: function (value) {
  5138. if (this._depthMask === value) {
  5139. return;
  5140. }
  5141. this._depthMask = value;
  5142. this._isDepthMaskDirty = true;
  5143. },
  5144. enumerable: true,
  5145. configurable: true
  5146. });
  5147. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5148. get: function () {
  5149. return this._depthTest;
  5150. },
  5151. set: function (value) {
  5152. if (this._depthTest === value) {
  5153. return;
  5154. }
  5155. this._depthTest = value;
  5156. this._isDepthTestDirty = true;
  5157. },
  5158. enumerable: true,
  5159. configurable: true
  5160. });
  5161. _DepthCullingState.prototype.reset = function () {
  5162. this._depthMask = true;
  5163. this._depthTest = true;
  5164. this._depthFunc = null;
  5165. this._cull = null;
  5166. this._cullFace = null;
  5167. this._zOffset = 0;
  5168. this._isDepthTestDirty = true;
  5169. this._isDepthMaskDirty = true;
  5170. this._isDepthFuncDirty = false;
  5171. this._isCullFaceDirty = false;
  5172. this._isCullDirty = false;
  5173. this._isZOffsetDirty = false;
  5174. };
  5175. _DepthCullingState.prototype.apply = function (gl) {
  5176. if (!this.isDirty) {
  5177. return;
  5178. }
  5179. // Cull
  5180. if (this._isCullDirty) {
  5181. if (this.cull) {
  5182. gl.enable(gl.CULL_FACE);
  5183. }
  5184. else {
  5185. gl.disable(gl.CULL_FACE);
  5186. }
  5187. this._isCullDirty = false;
  5188. }
  5189. // Cull face
  5190. if (this._isCullFaceDirty) {
  5191. gl.cullFace(this.cullFace);
  5192. this._isCullFaceDirty = false;
  5193. }
  5194. // Depth mask
  5195. if (this._isDepthMaskDirty) {
  5196. gl.depthMask(this.depthMask);
  5197. this._isDepthMaskDirty = false;
  5198. }
  5199. // Depth test
  5200. if (this._isDepthTestDirty) {
  5201. if (this.depthTest) {
  5202. gl.enable(gl.DEPTH_TEST);
  5203. }
  5204. else {
  5205. gl.disable(gl.DEPTH_TEST);
  5206. }
  5207. this._isDepthTestDirty = false;
  5208. }
  5209. // Depth func
  5210. if (this._isDepthFuncDirty) {
  5211. gl.depthFunc(this.depthFunc);
  5212. this._isDepthFuncDirty = false;
  5213. }
  5214. // zOffset
  5215. if (this._isZOffsetDirty) {
  5216. if (this.zOffset) {
  5217. gl.enable(gl.POLYGON_OFFSET_FILL);
  5218. gl.polygonOffset(this.zOffset, 0);
  5219. }
  5220. else {
  5221. gl.disable(gl.POLYGON_OFFSET_FILL);
  5222. }
  5223. this._isZOffsetDirty = false;
  5224. }
  5225. };
  5226. return _DepthCullingState;
  5227. })();
  5228. BABYLON._DepthCullingState = _DepthCullingState;
  5229. var _AlphaState = (function () {
  5230. function _AlphaState() {
  5231. this._isAlphaBlendDirty = false;
  5232. this._isBlendFunctionParametersDirty = false;
  5233. this._alphaBlend = false;
  5234. this._blendFunctionParameters = new Array(4);
  5235. }
  5236. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5237. get: function () {
  5238. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5239. },
  5240. enumerable: true,
  5241. configurable: true
  5242. });
  5243. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5244. get: function () {
  5245. return this._alphaBlend;
  5246. },
  5247. set: function (value) {
  5248. if (this._alphaBlend === value) {
  5249. return;
  5250. }
  5251. this._alphaBlend = value;
  5252. this._isAlphaBlendDirty = true;
  5253. },
  5254. enumerable: true,
  5255. configurable: true
  5256. });
  5257. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5258. if (this._blendFunctionParameters[0] === value0 &&
  5259. this._blendFunctionParameters[1] === value1 &&
  5260. this._blendFunctionParameters[2] === value2 &&
  5261. this._blendFunctionParameters[3] === value3) {
  5262. return;
  5263. }
  5264. this._blendFunctionParameters[0] = value0;
  5265. this._blendFunctionParameters[1] = value1;
  5266. this._blendFunctionParameters[2] = value2;
  5267. this._blendFunctionParameters[3] = value3;
  5268. this._isBlendFunctionParametersDirty = true;
  5269. };
  5270. _AlphaState.prototype.reset = function () {
  5271. this._alphaBlend = false;
  5272. this._blendFunctionParameters[0] = null;
  5273. this._blendFunctionParameters[1] = null;
  5274. this._blendFunctionParameters[2] = null;
  5275. this._blendFunctionParameters[3] = null;
  5276. this._isAlphaBlendDirty = true;
  5277. this._isBlendFunctionParametersDirty = false;
  5278. };
  5279. _AlphaState.prototype.apply = function (gl) {
  5280. if (!this.isDirty) {
  5281. return;
  5282. }
  5283. // Alpha blend
  5284. if (this._isAlphaBlendDirty) {
  5285. if (this._alphaBlend) {
  5286. gl.enable(gl.BLEND);
  5287. }
  5288. else {
  5289. gl.disable(gl.BLEND);
  5290. }
  5291. this._isAlphaBlendDirty = false;
  5292. }
  5293. // Alpha function
  5294. if (this._isBlendFunctionParametersDirty) {
  5295. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5296. this._isBlendFunctionParametersDirty = false;
  5297. }
  5298. };
  5299. return _AlphaState;
  5300. })();
  5301. BABYLON._AlphaState = _AlphaState;
  5302. var compileShader = function (gl, source, type, defines) {
  5303. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5304. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5305. gl.compileShader(shader);
  5306. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5307. throw new Error(gl.getShaderInfoLog(shader));
  5308. }
  5309. return shader;
  5310. };
  5311. var getWebGLTextureType = function (gl, type) {
  5312. var textureType = gl.UNSIGNED_BYTE;
  5313. if (type === Engine.TEXTURETYPE_FLOAT)
  5314. textureType = gl.FLOAT;
  5315. return textureType;
  5316. };
  5317. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5318. var magFilter = gl.NEAREST;
  5319. var minFilter = gl.NEAREST;
  5320. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5321. magFilter = gl.LINEAR;
  5322. if (generateMipMaps) {
  5323. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5324. }
  5325. else {
  5326. minFilter = gl.LINEAR;
  5327. }
  5328. }
  5329. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5330. magFilter = gl.LINEAR;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5333. }
  5334. else {
  5335. minFilter = gl.LINEAR;
  5336. }
  5337. }
  5338. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5339. magFilter = gl.NEAREST;
  5340. if (generateMipMaps) {
  5341. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5342. }
  5343. else {
  5344. minFilter = gl.NEAREST;
  5345. }
  5346. }
  5347. return {
  5348. min: minFilter,
  5349. mag: magFilter
  5350. };
  5351. };
  5352. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5354. var engine = scene.getEngine();
  5355. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5356. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5357. gl.bindTexture(gl.TEXTURE_2D, texture);
  5358. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5359. texture._baseWidth = width;
  5360. texture._baseHeight = height;
  5361. texture._width = potWidth;
  5362. texture._height = potHeight;
  5363. texture.isReady = true;
  5364. processFunction(potWidth, potHeight);
  5365. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5368. if (!noMipmap && !isCompressed) {
  5369. gl.generateMipmap(gl.TEXTURE_2D);
  5370. }
  5371. gl.bindTexture(gl.TEXTURE_2D, null);
  5372. engine._activeTexturesCache = [];
  5373. scene._removePendingData(texture);
  5374. };
  5375. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5376. var onload = function () {
  5377. loadedImages[index] = img;
  5378. loadedImages._internalCount++;
  5379. scene._removePendingData(img);
  5380. if (loadedImages._internalCount === 6) {
  5381. onfinish(loadedImages);
  5382. }
  5383. };
  5384. var onerror = function () {
  5385. scene._removePendingData(img);
  5386. };
  5387. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5388. scene._addPendingData(img);
  5389. };
  5390. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5391. var loadedImages = [];
  5392. loadedImages._internalCount = 0;
  5393. for (var index = 0; index < 6; index++) {
  5394. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5395. }
  5396. };
  5397. var EngineCapabilities = (function () {
  5398. function EngineCapabilities() {
  5399. }
  5400. return EngineCapabilities;
  5401. })();
  5402. BABYLON.EngineCapabilities = EngineCapabilities;
  5403. /**
  5404. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5405. */
  5406. var Engine = (function () {
  5407. /**
  5408. * @constructor
  5409. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5410. * @param {boolean} [antialias] - enable antialias
  5411. * @param options - further options to be sent to the getContext function
  5412. */
  5413. function Engine(canvas, antialias, options) {
  5414. var _this = this;
  5415. // Public members
  5416. this.isFullscreen = false;
  5417. this.isPointerLock = false;
  5418. this.cullBackFaces = true;
  5419. this.renderEvenInBackground = true;
  5420. // To enable/disable IDB support and avoid XHR on .manifest
  5421. this.enableOfflineSupport = true;
  5422. this.scenes = new Array();
  5423. this._windowIsBackground = false;
  5424. this._loadingDivBackgroundColor = "black";
  5425. this._drawCalls = 0;
  5426. this._renderingQueueLaunched = false;
  5427. this._activeRenderLoops = [];
  5428. // FPS
  5429. this.fpsRange = 60;
  5430. this.previousFramesDuration = [];
  5431. this.fps = 60;
  5432. this.deltaTime = 0;
  5433. // States
  5434. this._depthCullingState = new _DepthCullingState();
  5435. this._alphaState = new _AlphaState();
  5436. this._alphaMode = Engine.ALPHA_DISABLE;
  5437. // Cache
  5438. this._loadedTexturesCache = new Array();
  5439. this._activeTexturesCache = new Array();
  5440. this._compiledEffects = {};
  5441. this._uintIndicesCurrentlySet = false;
  5442. this._renderingCanvas = canvas;
  5443. options = options || {};
  5444. options.antialias = antialias;
  5445. if (options.preserveDrawingBuffer === undefined) {
  5446. options.preserveDrawingBuffer = false;
  5447. }
  5448. // GL
  5449. try {
  5450. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5451. }
  5452. catch (e) {
  5453. throw new Error("WebGL not supported");
  5454. }
  5455. if (!this._gl) {
  5456. throw new Error("WebGL not supported");
  5457. }
  5458. this._onBlur = function () {
  5459. _this._windowIsBackground = true;
  5460. };
  5461. this._onFocus = function () {
  5462. _this._windowIsBackground = false;
  5463. };
  5464. window.addEventListener("blur", this._onBlur);
  5465. window.addEventListener("focus", this._onFocus);
  5466. // Viewport
  5467. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5468. this.resize();
  5469. // Caps
  5470. this._caps = new EngineCapabilities();
  5471. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5472. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5473. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5474. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5475. // Infos
  5476. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5477. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5478. if (rendererInfo != null) {
  5479. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5480. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5481. }
  5482. if (!this._glVendor) {
  5483. this._glVendor = "Unknown vendor";
  5484. }
  5485. if (!this._glRenderer) {
  5486. this._glRenderer = "Unknown renderer";
  5487. }
  5488. // Extensions
  5489. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5490. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5491. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5492. 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');
  5493. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5494. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5495. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5496. this._caps.highPrecisionShaderSupported = true;
  5497. if (this._gl.getShaderPrecisionFormat) {
  5498. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5499. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5500. }
  5501. // Depth buffer
  5502. this.setDepthBuffer(true);
  5503. this.setDepthFunctionToLessOrEqual();
  5504. this.setDepthWrite(true);
  5505. // Fullscreen
  5506. this._onFullscreenChange = function () {
  5507. if (document.fullscreen !== undefined) {
  5508. _this.isFullscreen = document.fullscreen;
  5509. }
  5510. else if (document.mozFullScreen !== undefined) {
  5511. _this.isFullscreen = document.mozFullScreen;
  5512. }
  5513. else if (document.webkitIsFullScreen !== undefined) {
  5514. _this.isFullscreen = document.webkitIsFullScreen;
  5515. }
  5516. else if (document.msIsFullScreen !== undefined) {
  5517. _this.isFullscreen = document.msIsFullScreen;
  5518. }
  5519. // Pointer lock
  5520. if (_this.isFullscreen && _this._pointerLockRequested) {
  5521. canvas.requestPointerLock = canvas.requestPointerLock ||
  5522. canvas.msRequestPointerLock ||
  5523. canvas.mozRequestPointerLock ||
  5524. canvas.webkitRequestPointerLock;
  5525. if (canvas.requestPointerLock) {
  5526. canvas.requestPointerLock();
  5527. }
  5528. }
  5529. };
  5530. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5531. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5532. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5533. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5534. // Pointer lock
  5535. this._onPointerLockChange = function () {
  5536. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5537. document.webkitPointerLockElement === canvas ||
  5538. document.msPointerLockElement === canvas ||
  5539. document.pointerLockElement === canvas);
  5540. };
  5541. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5542. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5543. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5544. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5545. if (!Engine.audioEngine) {
  5546. Engine.audioEngine = new BABYLON.AudioEngine();
  5547. }
  5548. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5549. }
  5550. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5551. get: function () {
  5552. return Engine._ALPHA_DISABLE;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5558. get: function () {
  5559. return Engine._ALPHA_ONEONE;
  5560. },
  5561. enumerable: true,
  5562. configurable: true
  5563. });
  5564. Object.defineProperty(Engine, "ALPHA_ADD", {
  5565. get: function () {
  5566. return Engine._ALPHA_ADD;
  5567. },
  5568. enumerable: true,
  5569. configurable: true
  5570. });
  5571. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5572. get: function () {
  5573. return Engine._ALPHA_COMBINE;
  5574. },
  5575. enumerable: true,
  5576. configurable: true
  5577. });
  5578. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5579. get: function () {
  5580. return Engine._ALPHA_SUBTRACT;
  5581. },
  5582. enumerable: true,
  5583. configurable: true
  5584. });
  5585. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5586. get: function () {
  5587. return Engine._ALPHA_MULTIPLY;
  5588. },
  5589. enumerable: true,
  5590. configurable: true
  5591. });
  5592. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5593. get: function () {
  5594. return Engine._ALPHA_MAXIMIZED;
  5595. },
  5596. enumerable: true,
  5597. configurable: true
  5598. });
  5599. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5600. get: function () {
  5601. return Engine._DELAYLOADSTATE_NONE;
  5602. },
  5603. enumerable: true,
  5604. configurable: true
  5605. });
  5606. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5607. get: function () {
  5608. return Engine._DELAYLOADSTATE_LOADED;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5614. get: function () {
  5615. return Engine._DELAYLOADSTATE_LOADING;
  5616. },
  5617. enumerable: true,
  5618. configurable: true
  5619. });
  5620. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5621. get: function () {
  5622. return Engine._DELAYLOADSTATE_NOTLOADED;
  5623. },
  5624. enumerable: true,
  5625. configurable: true
  5626. });
  5627. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5628. get: function () {
  5629. return Engine._TEXTUREFORMAT_ALPHA;
  5630. },
  5631. enumerable: true,
  5632. configurable: true
  5633. });
  5634. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5635. get: function () {
  5636. return Engine._TEXTUREFORMAT_LUMINANCE;
  5637. },
  5638. enumerable: true,
  5639. configurable: true
  5640. });
  5641. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5642. get: function () {
  5643. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5644. },
  5645. enumerable: true,
  5646. configurable: true
  5647. });
  5648. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5649. get: function () {
  5650. return Engine._TEXTUREFORMAT_RGB;
  5651. },
  5652. enumerable: true,
  5653. configurable: true
  5654. });
  5655. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5656. get: function () {
  5657. return Engine._TEXTUREFORMAT_RGBA;
  5658. },
  5659. enumerable: true,
  5660. configurable: true
  5661. });
  5662. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5663. get: function () {
  5664. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5665. },
  5666. enumerable: true,
  5667. configurable: true
  5668. });
  5669. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5670. get: function () {
  5671. return Engine._TEXTURETYPE_FLOAT;
  5672. },
  5673. enumerable: true,
  5674. configurable: true
  5675. });
  5676. Object.defineProperty(Engine, "Version", {
  5677. get: function () {
  5678. return "2.2.0-beta";
  5679. },
  5680. enumerable: true,
  5681. configurable: true
  5682. });
  5683. Engine.prototype._prepareWorkingCanvas = function () {
  5684. if (this._workingCanvas) {
  5685. return;
  5686. }
  5687. this._workingCanvas = document.createElement("canvas");
  5688. this._workingContext = this._workingCanvas.getContext("2d");
  5689. };
  5690. Engine.prototype.getGlInfo = function () {
  5691. return {
  5692. vendor: this._glVendor,
  5693. renderer: this._glRenderer,
  5694. version: this._glVersion
  5695. };
  5696. };
  5697. Engine.prototype.getAspectRatio = function (camera) {
  5698. var viewport = camera.viewport;
  5699. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5700. };
  5701. Engine.prototype.getRenderWidth = function () {
  5702. if (this._currentRenderTarget) {
  5703. return this._currentRenderTarget._width;
  5704. }
  5705. return this._renderingCanvas.width;
  5706. };
  5707. Engine.prototype.getRenderHeight = function () {
  5708. if (this._currentRenderTarget) {
  5709. return this._currentRenderTarget._height;
  5710. }
  5711. return this._renderingCanvas.height;
  5712. };
  5713. Engine.prototype.getRenderingCanvas = function () {
  5714. return this._renderingCanvas;
  5715. };
  5716. Engine.prototype.getRenderingCanvasClientRect = function () {
  5717. return this._renderingCanvas.getBoundingClientRect();
  5718. };
  5719. Engine.prototype.setHardwareScalingLevel = function (level) {
  5720. this._hardwareScalingLevel = level;
  5721. this.resize();
  5722. };
  5723. Engine.prototype.getHardwareScalingLevel = function () {
  5724. return this._hardwareScalingLevel;
  5725. };
  5726. Engine.prototype.getLoadedTexturesCache = function () {
  5727. return this._loadedTexturesCache;
  5728. };
  5729. Engine.prototype.getCaps = function () {
  5730. return this._caps;
  5731. };
  5732. Object.defineProperty(Engine.prototype, "drawCalls", {
  5733. get: function () {
  5734. return this._drawCalls;
  5735. },
  5736. enumerable: true,
  5737. configurable: true
  5738. });
  5739. // Methods
  5740. Engine.prototype.resetDrawCalls = function () {
  5741. this._drawCalls = 0;
  5742. };
  5743. Engine.prototype.setDepthFunctionToGreater = function () {
  5744. this._depthCullingState.depthFunc = this._gl.GREATER;
  5745. };
  5746. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5747. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5748. };
  5749. Engine.prototype.setDepthFunctionToLess = function () {
  5750. this._depthCullingState.depthFunc = this._gl.LESS;
  5751. };
  5752. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5753. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5754. };
  5755. /**
  5756. * stop executing a render loop function and remove it from the execution array
  5757. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5758. */
  5759. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5760. if (!renderFunction) {
  5761. this._activeRenderLoops = [];
  5762. return;
  5763. }
  5764. var index = this._activeRenderLoops.indexOf(renderFunction);
  5765. if (index >= 0) {
  5766. this._activeRenderLoops.splice(index, 1);
  5767. }
  5768. };
  5769. Engine.prototype._renderLoop = function () {
  5770. var _this = this;
  5771. var shouldRender = true;
  5772. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5773. shouldRender = false;
  5774. }
  5775. if (shouldRender) {
  5776. // Start new frame
  5777. this.beginFrame();
  5778. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5779. var renderFunction = this._activeRenderLoops[index];
  5780. renderFunction();
  5781. }
  5782. // Present
  5783. this.endFrame();
  5784. }
  5785. if (this._activeRenderLoops.length > 0) {
  5786. // Register new frame
  5787. BABYLON.Tools.QueueNewFrame(function () {
  5788. _this._renderLoop();
  5789. });
  5790. }
  5791. else {
  5792. this._renderingQueueLaunched = false;
  5793. }
  5794. };
  5795. /**
  5796. * Register and execute a render loop. The engine can have more than one render function.
  5797. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5798. * @example
  5799. * engine.runRenderLoop(function () {
  5800. * scene.render()
  5801. * })
  5802. */
  5803. Engine.prototype.runRenderLoop = function (renderFunction) {
  5804. var _this = this;
  5805. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5806. return;
  5807. }
  5808. this._activeRenderLoops.push(renderFunction);
  5809. if (!this._renderingQueueLaunched) {
  5810. this._renderingQueueLaunched = true;
  5811. BABYLON.Tools.QueueNewFrame(function () {
  5812. _this._renderLoop();
  5813. });
  5814. }
  5815. };
  5816. /**
  5817. * Toggle full screen mode.
  5818. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5819. */
  5820. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5821. if (this.isFullscreen) {
  5822. BABYLON.Tools.ExitFullscreen();
  5823. }
  5824. else {
  5825. this._pointerLockRequested = requestPointerLock;
  5826. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5827. }
  5828. };
  5829. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5830. this.applyStates();
  5831. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5832. if (this._depthCullingState.depthMask) {
  5833. this._gl.clearDepth(1.0);
  5834. }
  5835. var mode = 0;
  5836. if (backBuffer)
  5837. mode |= this._gl.COLOR_BUFFER_BIT;
  5838. if (depthStencil && this._depthCullingState.depthMask)
  5839. mode |= this._gl.DEPTH_BUFFER_BIT;
  5840. this._gl.clear(mode);
  5841. };
  5842. /**
  5843. * Set the WebGL's viewport
  5844. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5845. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5846. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5847. */
  5848. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5849. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5850. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5851. var x = viewport.x || 0;
  5852. var y = viewport.y || 0;
  5853. this._cachedViewport = viewport;
  5854. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5855. };
  5856. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5857. this._cachedViewport = null;
  5858. this._gl.viewport(x, y, width, height);
  5859. };
  5860. Engine.prototype.beginFrame = function () {
  5861. this._measureFps();
  5862. };
  5863. Engine.prototype.endFrame = function () {
  5864. //this.flushFramebuffer();
  5865. };
  5866. /**
  5867. * resize the view according to the canvas' size.
  5868. * @example
  5869. * window.addEventListener("resize", function () {
  5870. * engine.resize();
  5871. * });
  5872. */
  5873. Engine.prototype.resize = function () {
  5874. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5875. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5876. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5877. };
  5878. /**
  5879. * force a specific size of the canvas
  5880. * @param {number} width - the new canvas' width
  5881. * @param {number} height - the new canvas' height
  5882. */
  5883. Engine.prototype.setSize = function (width, height) {
  5884. this._renderingCanvas.width = width;
  5885. this._renderingCanvas.height = height;
  5886. for (var index = 0; index < this.scenes.length; index++) {
  5887. var scene = this.scenes[index];
  5888. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5889. var cam = scene.cameras[camIndex];
  5890. cam._currentRenderId = 0;
  5891. }
  5892. }
  5893. };
  5894. Engine.prototype.bindFramebuffer = function (texture) {
  5895. this._currentRenderTarget = texture;
  5896. var gl = this._gl;
  5897. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5898. this._gl.viewport(0, 0, texture._width, texture._height);
  5899. this.wipeCaches();
  5900. };
  5901. Engine.prototype.unBindFramebuffer = function (texture) {
  5902. this._currentRenderTarget = null;
  5903. if (texture.generateMipMaps) {
  5904. var gl = this._gl;
  5905. gl.bindTexture(gl.TEXTURE_2D, texture);
  5906. gl.generateMipmap(gl.TEXTURE_2D);
  5907. gl.bindTexture(gl.TEXTURE_2D, null);
  5908. }
  5909. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5910. };
  5911. Engine.prototype.flushFramebuffer = function () {
  5912. this._gl.flush();
  5913. };
  5914. Engine.prototype.restoreDefaultFramebuffer = function () {
  5915. this._currentRenderTarget = null;
  5916. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5917. this.setViewport(this._cachedViewport);
  5918. this.wipeCaches();
  5919. };
  5920. // VBOs
  5921. Engine.prototype._resetVertexBufferBinding = function () {
  5922. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5923. this._cachedVertexBuffers = null;
  5924. };
  5925. Engine.prototype.createVertexBuffer = function (vertices) {
  5926. var vbo = this._gl.createBuffer();
  5927. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5928. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5929. this._resetVertexBufferBinding();
  5930. vbo.references = 1;
  5931. return vbo;
  5932. };
  5933. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5934. var vbo = this._gl.createBuffer();
  5935. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5936. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5937. this._resetVertexBufferBinding();
  5938. vbo.references = 1;
  5939. return vbo;
  5940. };
  5941. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5942. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5943. if (offset === undefined) {
  5944. offset = 0;
  5945. }
  5946. if (vertices instanceof Float32Array) {
  5947. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5948. }
  5949. else {
  5950. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5951. }
  5952. this._resetVertexBufferBinding();
  5953. };
  5954. Engine.prototype._resetIndexBufferBinding = function () {
  5955. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5956. this._cachedIndexBuffer = null;
  5957. };
  5958. Engine.prototype.createIndexBuffer = function (indices) {
  5959. var vbo = this._gl.createBuffer();
  5960. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5961. // Check for 32 bits indices
  5962. var arrayBuffer;
  5963. var need32Bits = false;
  5964. if (this._caps.uintIndices) {
  5965. for (var index = 0; index < indices.length; index++) {
  5966. if (indices[index] > 65535) {
  5967. need32Bits = true;
  5968. break;
  5969. }
  5970. }
  5971. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5972. }
  5973. else {
  5974. arrayBuffer = new Uint16Array(indices);
  5975. }
  5976. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5977. this._resetIndexBufferBinding();
  5978. vbo.references = 1;
  5979. vbo.is32Bits = need32Bits;
  5980. return vbo;
  5981. };
  5982. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5983. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5984. this._cachedVertexBuffers = vertexBuffer;
  5985. this._cachedEffectForVertexBuffers = effect;
  5986. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5987. var offset = 0;
  5988. for (var index = 0; index < vertexDeclaration.length; index++) {
  5989. var order = effect.getAttributeLocation(index);
  5990. if (order >= 0) {
  5991. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5992. }
  5993. offset += vertexDeclaration[index] * 4;
  5994. }
  5995. }
  5996. if (this._cachedIndexBuffer !== indexBuffer) {
  5997. this._cachedIndexBuffer = indexBuffer;
  5998. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5999. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6000. }
  6001. };
  6002. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6003. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6004. this._cachedVertexBuffers = vertexBuffers;
  6005. this._cachedEffectForVertexBuffers = effect;
  6006. var attributes = effect.getAttributesNames();
  6007. for (var index = 0; index < attributes.length; index++) {
  6008. var order = effect.getAttributeLocation(index);
  6009. if (order >= 0) {
  6010. var vertexBuffer = vertexBuffers[attributes[index]];
  6011. if (!vertexBuffer) {
  6012. continue;
  6013. }
  6014. var stride = vertexBuffer.getStrideSize();
  6015. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6016. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6017. }
  6018. }
  6019. }
  6020. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6021. this._cachedIndexBuffer = indexBuffer;
  6022. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6023. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6024. }
  6025. };
  6026. Engine.prototype._releaseBuffer = function (buffer) {
  6027. buffer.references--;
  6028. if (buffer.references === 0) {
  6029. this._gl.deleteBuffer(buffer);
  6030. return true;
  6031. }
  6032. return false;
  6033. };
  6034. Engine.prototype.createInstancesBuffer = function (capacity) {
  6035. var buffer = this._gl.createBuffer();
  6036. buffer.capacity = capacity;
  6037. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6038. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6039. return buffer;
  6040. };
  6041. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6042. this._gl.deleteBuffer(buffer);
  6043. };
  6044. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6045. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6047. for (var index = 0; index < 4; index++) {
  6048. var offsetLocation = offsetLocations[index];
  6049. this._gl.enableVertexAttribArray(offsetLocation);
  6050. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6051. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6052. }
  6053. };
  6054. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6055. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6056. for (var index = 0; index < 4; index++) {
  6057. var offsetLocation = offsetLocations[index];
  6058. this._gl.disableVertexAttribArray(offsetLocation);
  6059. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6060. }
  6061. };
  6062. Engine.prototype.applyStates = function () {
  6063. this._depthCullingState.apply(this._gl);
  6064. this._alphaState.apply(this._gl);
  6065. };
  6066. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6067. // Apply states
  6068. this.applyStates();
  6069. this._drawCalls++;
  6070. // Render
  6071. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6072. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6073. if (instancesCount) {
  6074. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6075. return;
  6076. }
  6077. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6078. };
  6079. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6080. // Apply states
  6081. this.applyStates();
  6082. this._drawCalls++;
  6083. if (instancesCount) {
  6084. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6085. return;
  6086. }
  6087. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6088. };
  6089. // Shaders
  6090. Engine.prototype._releaseEffect = function (effect) {
  6091. if (this._compiledEffects[effect._key]) {
  6092. delete this._compiledEffects[effect._key];
  6093. if (effect.getProgram()) {
  6094. this._gl.deleteProgram(effect.getProgram());
  6095. }
  6096. }
  6097. };
  6098. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6099. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6100. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6101. var name = vertex + "+" + fragment + "@" + defines;
  6102. if (this._compiledEffects[name]) {
  6103. return this._compiledEffects[name];
  6104. }
  6105. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6106. effect._key = name;
  6107. this._compiledEffects[name] = effect;
  6108. return effect;
  6109. };
  6110. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6111. if (uniformsNames === void 0) { uniformsNames = []; }
  6112. if (samplers === void 0) { samplers = []; }
  6113. if (defines === void 0) { defines = ""; }
  6114. return this.createEffect({
  6115. vertex: "particles",
  6116. fragmentElement: fragmentName
  6117. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6118. };
  6119. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6120. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6121. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6122. var shaderProgram = this._gl.createProgram();
  6123. this._gl.attachShader(shaderProgram, vertexShader);
  6124. this._gl.attachShader(shaderProgram, fragmentShader);
  6125. this._gl.linkProgram(shaderProgram);
  6126. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6127. if (!linked) {
  6128. var error = this._gl.getProgramInfoLog(shaderProgram);
  6129. if (error) {
  6130. throw new Error(error);
  6131. }
  6132. }
  6133. this._gl.deleteShader(vertexShader);
  6134. this._gl.deleteShader(fragmentShader);
  6135. return shaderProgram;
  6136. };
  6137. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6138. var results = [];
  6139. for (var index = 0; index < uniformsNames.length; index++) {
  6140. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6141. }
  6142. return results;
  6143. };
  6144. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6145. var results = [];
  6146. for (var index = 0; index < attributesNames.length; index++) {
  6147. try {
  6148. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6149. }
  6150. catch (e) {
  6151. results.push(-1);
  6152. }
  6153. }
  6154. return results;
  6155. };
  6156. Engine.prototype.enableEffect = function (effect) {
  6157. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6158. if (effect && effect.onBind) {
  6159. effect.onBind(effect);
  6160. }
  6161. return;
  6162. }
  6163. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6164. // Use program
  6165. this._gl.useProgram(effect.getProgram());
  6166. for (var i in this._vertexAttribArrays) {
  6167. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6168. continue;
  6169. }
  6170. this._vertexAttribArrays[i] = false;
  6171. this._gl.disableVertexAttribArray(i);
  6172. }
  6173. var attributesCount = effect.getAttributesCount();
  6174. for (var index = 0; index < attributesCount; index++) {
  6175. // Attributes
  6176. var order = effect.getAttributeLocation(index);
  6177. if (order >= 0) {
  6178. this._vertexAttribArrays[order] = true;
  6179. this._gl.enableVertexAttribArray(order);
  6180. }
  6181. }
  6182. this._currentEffect = effect;
  6183. if (effect.onBind) {
  6184. effect.onBind(effect);
  6185. }
  6186. };
  6187. Engine.prototype.setArray = function (uniform, array) {
  6188. if (!uniform)
  6189. return;
  6190. this._gl.uniform1fv(uniform, array);
  6191. };
  6192. Engine.prototype.setArray2 = function (uniform, array) {
  6193. if (!uniform || array.length % 2 !== 0)
  6194. return;
  6195. this._gl.uniform2fv(uniform, array);
  6196. };
  6197. Engine.prototype.setArray3 = function (uniform, array) {
  6198. if (!uniform || array.length % 3 !== 0)
  6199. return;
  6200. this._gl.uniform3fv(uniform, array);
  6201. };
  6202. Engine.prototype.setArray4 = function (uniform, array) {
  6203. if (!uniform || array.length % 4 !== 0)
  6204. return;
  6205. this._gl.uniform4fv(uniform, array);
  6206. };
  6207. Engine.prototype.setMatrices = function (uniform, matrices) {
  6208. if (!uniform)
  6209. return;
  6210. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6211. };
  6212. Engine.prototype.setMatrix = function (uniform, matrix) {
  6213. if (!uniform)
  6214. return;
  6215. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6216. };
  6217. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6218. if (!uniform)
  6219. return;
  6220. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6221. };
  6222. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6223. if (!uniform)
  6224. return;
  6225. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6226. };
  6227. Engine.prototype.setFloat = function (uniform, value) {
  6228. if (!uniform)
  6229. return;
  6230. this._gl.uniform1f(uniform, value);
  6231. };
  6232. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6233. if (!uniform)
  6234. return;
  6235. this._gl.uniform2f(uniform, x, y);
  6236. };
  6237. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6238. if (!uniform)
  6239. return;
  6240. this._gl.uniform3f(uniform, x, y, z);
  6241. };
  6242. Engine.prototype.setBool = function (uniform, bool) {
  6243. if (!uniform)
  6244. return;
  6245. this._gl.uniform1i(uniform, bool);
  6246. };
  6247. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6248. if (!uniform)
  6249. return;
  6250. this._gl.uniform4f(uniform, x, y, z, w);
  6251. };
  6252. Engine.prototype.setColor3 = function (uniform, color3) {
  6253. if (!uniform)
  6254. return;
  6255. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6256. };
  6257. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6258. if (!uniform)
  6259. return;
  6260. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6261. };
  6262. // States
  6263. Engine.prototype.setState = function (culling, zOffset, force) {
  6264. if (zOffset === void 0) { zOffset = 0; }
  6265. // Culling
  6266. if (this._depthCullingState.cull !== culling || force) {
  6267. if (culling) {
  6268. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6269. this._depthCullingState.cull = true;
  6270. }
  6271. else {
  6272. this._depthCullingState.cull = false;
  6273. }
  6274. }
  6275. // Z offset
  6276. this._depthCullingState.zOffset = zOffset;
  6277. };
  6278. Engine.prototype.setDepthBuffer = function (enable) {
  6279. this._depthCullingState.depthTest = enable;
  6280. };
  6281. Engine.prototype.getDepthWrite = function () {
  6282. return this._depthCullingState.depthMask;
  6283. };
  6284. Engine.prototype.setDepthWrite = function (enable) {
  6285. this._depthCullingState.depthMask = enable;
  6286. };
  6287. Engine.prototype.setColorWrite = function (enable) {
  6288. this._gl.colorMask(enable, enable, enable, enable);
  6289. };
  6290. Engine.prototype.setAlphaMode = function (mode) {
  6291. if (this._alphaMode == mode) {
  6292. return;
  6293. }
  6294. switch (mode) {
  6295. case Engine.ALPHA_DISABLE:
  6296. this.setDepthWrite(true);
  6297. this._alphaState.alphaBlend = false;
  6298. break;
  6299. case Engine.ALPHA_COMBINE:
  6300. this.setDepthWrite(false);
  6301. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6302. this._alphaState.alphaBlend = true;
  6303. break;
  6304. case Engine.ALPHA_ONEONE:
  6305. this.setDepthWrite(false);
  6306. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6307. this._alphaState.alphaBlend = true;
  6308. break;
  6309. case Engine.ALPHA_ADD:
  6310. this.setDepthWrite(false);
  6311. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6312. this._alphaState.alphaBlend = true;
  6313. break;
  6314. case Engine.ALPHA_SUBTRACT:
  6315. this.setDepthWrite(false);
  6316. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6317. this._alphaState.alphaBlend = true;
  6318. break;
  6319. case Engine.ALPHA_MULTIPLY:
  6320. this.setDepthWrite(false);
  6321. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6322. this._alphaState.alphaBlend = true;
  6323. break;
  6324. case Engine.ALPHA_MAXIMIZED:
  6325. this.setDepthWrite(false);
  6326. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6327. this._alphaState.alphaBlend = true;
  6328. break;
  6329. }
  6330. this._alphaMode = mode;
  6331. };
  6332. Engine.prototype.getAlphaMode = function () {
  6333. return this._alphaMode;
  6334. };
  6335. Engine.prototype.setAlphaTesting = function (enable) {
  6336. this._alphaTest = enable;
  6337. };
  6338. Engine.prototype.getAlphaTesting = function () {
  6339. return this._alphaTest;
  6340. };
  6341. // Textures
  6342. Engine.prototype.wipeCaches = function () {
  6343. this._activeTexturesCache = [];
  6344. this._currentEffect = null;
  6345. this._depthCullingState.reset();
  6346. this._alphaState.reset();
  6347. this._cachedVertexBuffers = null;
  6348. this._cachedIndexBuffer = null;
  6349. this._cachedEffectForVertexBuffers = null;
  6350. };
  6351. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6352. var gl = this._gl;
  6353. gl.bindTexture(gl.TEXTURE_2D, texture);
  6354. var magFilter = gl.NEAREST;
  6355. var minFilter = gl.NEAREST;
  6356. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6357. magFilter = gl.LINEAR;
  6358. minFilter = gl.LINEAR;
  6359. }
  6360. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6361. magFilter = gl.LINEAR;
  6362. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6363. }
  6364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6366. gl.bindTexture(gl.TEXTURE_2D, null);
  6367. texture.samplingMode = samplingMode;
  6368. };
  6369. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6370. var _this = this;
  6371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6372. if (onLoad === void 0) { onLoad = null; }
  6373. if (onError === void 0) { onError = null; }
  6374. if (buffer === void 0) { buffer = null; }
  6375. var texture = this._gl.createTexture();
  6376. var extension;
  6377. var fromData = false;
  6378. if (url.substr(0, 5) === "data:") {
  6379. fromData = true;
  6380. }
  6381. if (!fromData)
  6382. extension = url.substr(url.length - 4, 4).toLowerCase();
  6383. else {
  6384. var oldUrl = url;
  6385. fromData = oldUrl.split(':');
  6386. url = oldUrl;
  6387. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6388. }
  6389. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6390. var isTGA = (extension === ".tga");
  6391. scene._addPendingData(texture);
  6392. texture.url = url;
  6393. texture.noMipmap = noMipmap;
  6394. texture.references = 1;
  6395. texture.samplingMode = samplingMode;
  6396. this._loadedTexturesCache.push(texture);
  6397. var onerror = function () {
  6398. scene._removePendingData(texture);
  6399. if (onError) {
  6400. onError();
  6401. }
  6402. };
  6403. if (isTGA) {
  6404. var callback = function (arrayBuffer) {
  6405. var data = new Uint8Array(arrayBuffer);
  6406. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6407. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6408. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6409. if (onLoad) {
  6410. onLoad();
  6411. }
  6412. }, samplingMode);
  6413. };
  6414. if (!(fromData instanceof Array))
  6415. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6416. callback(arrayBuffer);
  6417. }, onerror, scene.database, true);
  6418. else
  6419. callback(buffer);
  6420. }
  6421. else if (isDDS) {
  6422. callback = function (data) {
  6423. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6424. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6425. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6426. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6427. if (onLoad) {
  6428. onLoad();
  6429. }
  6430. }, samplingMode);
  6431. };
  6432. if (!(fromData instanceof Array))
  6433. BABYLON.Tools.LoadFile(url, function (data) {
  6434. callback(data);
  6435. }, onerror, scene.database, true);
  6436. else
  6437. callback(buffer);
  6438. }
  6439. else {
  6440. var onload = function (img) {
  6441. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6442. var isPot = (img.width === potWidth && img.height === potHeight);
  6443. if (!isPot) {
  6444. _this._prepareWorkingCanvas();
  6445. _this._workingCanvas.width = potWidth;
  6446. _this._workingCanvas.height = potHeight;
  6447. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6448. _this._workingContext.imageSmoothingEnabled = false;
  6449. _this._workingContext.mozImageSmoothingEnabled = false;
  6450. _this._workingContext.oImageSmoothingEnabled = false;
  6451. _this._workingContext.webkitImageSmoothingEnabled = false;
  6452. _this._workingContext.msImageSmoothingEnabled = false;
  6453. }
  6454. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6455. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6456. _this._workingContext.imageSmoothingEnabled = true;
  6457. _this._workingContext.mozImageSmoothingEnabled = true;
  6458. _this._workingContext.oImageSmoothingEnabled = true;
  6459. _this._workingContext.webkitImageSmoothingEnabled = true;
  6460. _this._workingContext.msImageSmoothingEnabled = true;
  6461. }
  6462. }
  6463. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6464. if (onLoad) {
  6465. onLoad();
  6466. }
  6467. }, samplingMode);
  6468. };
  6469. if (!(fromData instanceof Array))
  6470. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6471. else
  6472. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6473. }
  6474. return texture;
  6475. };
  6476. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6477. if (compression === void 0) { compression = null; }
  6478. var internalFormat = this._gl.RGBA;
  6479. switch (format) {
  6480. case Engine.TEXTUREFORMAT_ALPHA:
  6481. internalFormat = this._gl.ALPHA;
  6482. break;
  6483. case Engine.TEXTUREFORMAT_LUMINANCE:
  6484. internalFormat = this._gl.LUMINANCE;
  6485. break;
  6486. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6487. internalFormat = this._gl.LUMINANCE_ALPHA;
  6488. break;
  6489. case Engine.TEXTUREFORMAT_RGB:
  6490. internalFormat = this._gl.RGB;
  6491. break;
  6492. case Engine.TEXTUREFORMAT_RGBA:
  6493. internalFormat = this._gl.RGBA;
  6494. break;
  6495. }
  6496. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6497. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6498. if (compression) {
  6499. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6500. }
  6501. else {
  6502. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6503. }
  6504. if (texture.generateMipMaps) {
  6505. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6506. }
  6507. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6508. this._activeTexturesCache = [];
  6509. texture.isReady = true;
  6510. };
  6511. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6512. if (compression === void 0) { compression = null; }
  6513. var texture = this._gl.createTexture();
  6514. texture._baseWidth = width;
  6515. texture._baseHeight = height;
  6516. texture._width = width;
  6517. texture._height = height;
  6518. texture.references = 1;
  6519. this.updateRawTexture(texture, data, format, invertY, compression);
  6520. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6521. // Filters
  6522. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6523. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6524. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6525. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6526. texture.samplingMode = samplingMode;
  6527. this._loadedTexturesCache.push(texture);
  6528. return texture;
  6529. };
  6530. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6531. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6532. var texture = this._gl.createTexture();
  6533. texture._baseWidth = width;
  6534. texture._baseHeight = height;
  6535. if (forceExponantOfTwo) {
  6536. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6537. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6538. }
  6539. this._activeTexturesCache = [];
  6540. texture._width = width;
  6541. texture._height = height;
  6542. texture.isReady = false;
  6543. texture.generateMipMaps = generateMipMaps;
  6544. texture.references = 1;
  6545. texture.samplingMode = samplingMode;
  6546. this.updateTextureSamplingMode(samplingMode, texture);
  6547. this._loadedTexturesCache.push(texture);
  6548. return texture;
  6549. };
  6550. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6551. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6552. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6553. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6554. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6555. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6556. };
  6557. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6558. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6559. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6560. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6561. if (texture.generateMipMaps) {
  6562. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6563. }
  6564. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6565. this._activeTexturesCache = [];
  6566. texture.isReady = true;
  6567. };
  6568. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6569. if (texture._isDisabled) {
  6570. return;
  6571. }
  6572. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6573. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6574. try {
  6575. // Testing video texture support
  6576. if (this._videoTextureSupported === undefined) {
  6577. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6578. if (this._gl.getError() !== 0) {
  6579. this._videoTextureSupported = false;
  6580. }
  6581. else {
  6582. this._videoTextureSupported = true;
  6583. }
  6584. }
  6585. // Copy video through the current working canvas if video texture is not supported
  6586. if (!this._videoTextureSupported) {
  6587. if (!texture._workingCanvas) {
  6588. texture._workingCanvas = document.createElement("canvas");
  6589. texture._workingContext = texture._workingCanvas.getContext("2d");
  6590. texture._workingCanvas.width = texture._width;
  6591. texture._workingCanvas.height = texture._height;
  6592. }
  6593. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6594. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6595. }
  6596. else {
  6597. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6598. }
  6599. if (texture.generateMipMaps) {
  6600. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6601. }
  6602. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6603. this._activeTexturesCache = [];
  6604. texture.isReady = true;
  6605. }
  6606. catch (ex) {
  6607. // Something unexpected
  6608. // Let's disable the texture
  6609. texture._isDisabled = true;
  6610. }
  6611. };
  6612. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6613. // old version had a "generateMipMaps" arg instead of options.
  6614. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6615. // in the same way, generateDepthBuffer is defaulted to true
  6616. var generateMipMaps = false;
  6617. var generateDepthBuffer = true;
  6618. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6619. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6620. if (options !== undefined) {
  6621. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6622. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6623. type = options.type === undefined ? type : options.type;
  6624. if (options.samplingMode !== undefined) {
  6625. samplingMode = options.samplingMode;
  6626. }
  6627. if (type === Engine.TEXTURETYPE_FLOAT) {
  6628. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6629. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6630. }
  6631. }
  6632. var gl = this._gl;
  6633. var texture = gl.createTexture();
  6634. gl.bindTexture(gl.TEXTURE_2D, texture);
  6635. var width = size.width || size;
  6636. var height = size.height || size;
  6637. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6638. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6639. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6640. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6641. }
  6642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6646. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6647. var depthBuffer;
  6648. // Create the depth buffer
  6649. if (generateDepthBuffer) {
  6650. depthBuffer = gl.createRenderbuffer();
  6651. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6652. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6653. }
  6654. // Create the framebuffer
  6655. var framebuffer = gl.createFramebuffer();
  6656. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6657. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6658. if (generateDepthBuffer) {
  6659. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6660. }
  6661. if (generateMipMaps) {
  6662. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6663. }
  6664. // Unbind
  6665. gl.bindTexture(gl.TEXTURE_2D, null);
  6666. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6667. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6668. texture._framebuffer = framebuffer;
  6669. if (generateDepthBuffer) {
  6670. texture._depthBuffer = depthBuffer;
  6671. }
  6672. texture._width = width;
  6673. texture._height = height;
  6674. texture.isReady = true;
  6675. texture.generateMipMaps = generateMipMaps;
  6676. texture.references = 1;
  6677. texture.samplingMode = samplingMode;
  6678. this._activeTexturesCache = [];
  6679. this._loadedTexturesCache.push(texture);
  6680. return texture;
  6681. };
  6682. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6683. var _this = this;
  6684. var gl = this._gl;
  6685. var texture = gl.createTexture();
  6686. texture.isCube = true;
  6687. texture.url = rootUrl;
  6688. texture.references = 1;
  6689. this._loadedTexturesCache.push(texture);
  6690. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6691. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6692. if (isDDS) {
  6693. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6694. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6695. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6696. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6697. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6698. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6699. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6700. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6701. }
  6702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6706. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6707. _this._activeTexturesCache = [];
  6708. texture._width = info.width;
  6709. texture._height = info.height;
  6710. texture.isReady = true;
  6711. }, null, null, true);
  6712. }
  6713. else {
  6714. cascadeLoad(rootUrl, scene, function (imgs) {
  6715. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6716. var height = width;
  6717. _this._prepareWorkingCanvas();
  6718. _this._workingCanvas.width = width;
  6719. _this._workingCanvas.height = height;
  6720. var faces = [
  6721. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6722. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6723. ];
  6724. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6725. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6726. for (var index = 0; index < faces.length; index++) {
  6727. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6728. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6729. }
  6730. if (!noMipmap) {
  6731. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6732. }
  6733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6737. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6738. _this._activeTexturesCache = [];
  6739. texture._width = width;
  6740. texture._height = height;
  6741. texture.isReady = true;
  6742. }, extensions);
  6743. }
  6744. return texture;
  6745. };
  6746. Engine.prototype._releaseTexture = function (texture) {
  6747. var gl = this._gl;
  6748. if (texture._framebuffer) {
  6749. gl.deleteFramebuffer(texture._framebuffer);
  6750. }
  6751. if (texture._depthBuffer) {
  6752. gl.deleteRenderbuffer(texture._depthBuffer);
  6753. }
  6754. gl.deleteTexture(texture);
  6755. // Unbind channels
  6756. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6757. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6758. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6759. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6760. this._activeTexturesCache[channel] = null;
  6761. }
  6762. var index = this._loadedTexturesCache.indexOf(texture);
  6763. if (index !== -1) {
  6764. this._loadedTexturesCache.splice(index, 1);
  6765. }
  6766. };
  6767. Engine.prototype.bindSamplers = function (effect) {
  6768. this._gl.useProgram(effect.getProgram());
  6769. var samplers = effect.getSamplers();
  6770. for (var index = 0; index < samplers.length; index++) {
  6771. var uniform = effect.getUniform(samplers[index]);
  6772. this._gl.uniform1i(uniform, index);
  6773. }
  6774. this._currentEffect = null;
  6775. };
  6776. Engine.prototype._bindTexture = function (channel, texture) {
  6777. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6778. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6779. this._activeTexturesCache[channel] = null;
  6780. };
  6781. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6782. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6783. };
  6784. Engine.prototype.setTexture = function (channel, texture) {
  6785. if (channel < 0) {
  6786. return;
  6787. }
  6788. // Not ready?
  6789. if (!texture || !texture.isReady()) {
  6790. if (this._activeTexturesCache[channel] != null) {
  6791. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6792. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6793. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6794. this._activeTexturesCache[channel] = null;
  6795. }
  6796. return;
  6797. }
  6798. // Video
  6799. if (texture instanceof BABYLON.VideoTexture) {
  6800. if (texture.update()) {
  6801. this._activeTexturesCache[channel] = null;
  6802. }
  6803. }
  6804. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6805. texture.delayLoad();
  6806. return;
  6807. }
  6808. if (this._activeTexturesCache[channel] === texture) {
  6809. return;
  6810. }
  6811. this._activeTexturesCache[channel] = texture;
  6812. var internalTexture = texture.getInternalTexture();
  6813. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6814. if (internalTexture.isCube) {
  6815. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6816. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6817. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6818. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6819. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6820. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6821. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6822. }
  6823. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6824. }
  6825. else {
  6826. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6827. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6828. internalTexture._cachedWrapU = texture.wrapU;
  6829. switch (texture.wrapU) {
  6830. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6832. break;
  6833. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6834. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6835. break;
  6836. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6837. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6838. break;
  6839. }
  6840. }
  6841. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6842. internalTexture._cachedWrapV = texture.wrapV;
  6843. switch (texture.wrapV) {
  6844. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6846. break;
  6847. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6848. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6849. break;
  6850. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6852. break;
  6853. }
  6854. }
  6855. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6856. }
  6857. };
  6858. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6859. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6860. var value = texture.anisotropicFilteringLevel;
  6861. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6862. value = 1;
  6863. }
  6864. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6865. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6866. texture._cachedAnisotropicFilteringLevel = value;
  6867. }
  6868. };
  6869. Engine.prototype.readPixels = function (x, y, width, height) {
  6870. var data = new Uint8Array(height * width * 4);
  6871. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6872. return data;
  6873. };
  6874. // Dispose
  6875. Engine.prototype.dispose = function () {
  6876. this.hideLoadingUI();
  6877. this.stopRenderLoop();
  6878. // Release scenes
  6879. while (this.scenes.length) {
  6880. this.scenes[0].dispose();
  6881. }
  6882. // Release audio engine
  6883. Engine.audioEngine.dispose();
  6884. // Release effects
  6885. for (var name in this._compiledEffects) {
  6886. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6887. }
  6888. // Unbind
  6889. for (var i in this._vertexAttribArrays) {
  6890. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6891. continue;
  6892. }
  6893. this._gl.disableVertexAttribArray(i);
  6894. }
  6895. this._gl = null;
  6896. // Events
  6897. window.removeEventListener("blur", this._onBlur);
  6898. window.removeEventListener("focus", this._onFocus);
  6899. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6900. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6901. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6902. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6903. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6904. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6905. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6906. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6907. };
  6908. // Loading screen
  6909. Engine.prototype.displayLoadingUI = function () {
  6910. var _this = this;
  6911. this._loadingDiv = document.createElement("div");
  6912. this._loadingDiv.style.opacity = "0";
  6913. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6914. // Loading text
  6915. this._loadingTextDiv = document.createElement("div");
  6916. this._loadingTextDiv.style.position = "absolute";
  6917. this._loadingTextDiv.style.left = "0";
  6918. this._loadingTextDiv.style.top = "50%";
  6919. this._loadingTextDiv.style.marginTop = "80px";
  6920. this._loadingTextDiv.style.width = "100%";
  6921. this._loadingTextDiv.style.height = "20px";
  6922. this._loadingTextDiv.style.fontFamily = "Arial";
  6923. this._loadingTextDiv.style.fontSize = "14px";
  6924. this._loadingTextDiv.style.color = "white";
  6925. this._loadingTextDiv.style.textAlign = "center";
  6926. this._loadingTextDiv.innerHTML = "Loading";
  6927. this._loadingDiv.appendChild(this._loadingTextDiv);
  6928. // Loading img
  6929. var imgBack = new Image();
  6930. 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==";
  6931. imgBack.style.position = "absolute";
  6932. imgBack.style.left = "50%";
  6933. imgBack.style.top = "50%";
  6934. imgBack.style.marginLeft = "-50px";
  6935. imgBack.style.marginTop = "-50px";
  6936. imgBack.style.transition = "transform 1.0s ease";
  6937. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6938. var deg = 360;
  6939. var onTransitionEnd = function () {
  6940. deg += 360;
  6941. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6942. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6943. };
  6944. imgBack.addEventListener("transitionend", onTransitionEnd);
  6945. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6946. this._loadingDiv.appendChild(imgBack);
  6947. // front image
  6948. var imgFront = new Image();
  6949. 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=";
  6950. imgFront.style.position = "absolute";
  6951. imgFront.style.left = "50%";
  6952. imgFront.style.top = "50%";
  6953. imgFront.style.marginLeft = "-50px";
  6954. imgFront.style.marginTop = "-50px";
  6955. this._loadingDiv.appendChild(imgFront);
  6956. // Resize
  6957. this._resizeLoadingUI = function () {
  6958. var canvasRect = _this.getRenderingCanvasClientRect();
  6959. _this._loadingDiv.style.position = "absolute";
  6960. _this._loadingDiv.style.left = canvasRect.left + "px";
  6961. _this._loadingDiv.style.top = canvasRect.top + "px";
  6962. _this._loadingDiv.style.width = canvasRect.width + "px";
  6963. _this._loadingDiv.style.height = canvasRect.height + "px";
  6964. };
  6965. this._resizeLoadingUI();
  6966. window.addEventListener("resize", this._resizeLoadingUI);
  6967. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6968. document.body.appendChild(this._loadingDiv);
  6969. setTimeout(function () {
  6970. _this._loadingDiv.style.opacity = "1";
  6971. imgBack.style.transform = "rotateZ(360deg)";
  6972. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6973. }, 0);
  6974. };
  6975. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6976. set: function (text) {
  6977. if (!this._loadingDiv) {
  6978. return;
  6979. }
  6980. this._loadingTextDiv.innerHTML = text;
  6981. },
  6982. enumerable: true,
  6983. configurable: true
  6984. });
  6985. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6986. get: function () {
  6987. return this._loadingDivBackgroundColor;
  6988. },
  6989. set: function (color) {
  6990. this._loadingDivBackgroundColor = color;
  6991. if (!this._loadingDiv) {
  6992. return;
  6993. }
  6994. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6995. },
  6996. enumerable: true,
  6997. configurable: true
  6998. });
  6999. Engine.prototype.hideLoadingUI = function () {
  7000. var _this = this;
  7001. if (!this._loadingDiv) {
  7002. return;
  7003. }
  7004. var onTransitionEnd = function () {
  7005. if (!_this._loadingDiv) {
  7006. return;
  7007. }
  7008. document.body.removeChild(_this._loadingDiv);
  7009. window.removeEventListener("resize", _this._resizeLoadingUI);
  7010. _this._loadingDiv = null;
  7011. };
  7012. this._loadingDiv.style.opacity = "0";
  7013. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7014. };
  7015. // FPS
  7016. Engine.prototype.getFps = function () {
  7017. return this.fps;
  7018. };
  7019. Engine.prototype.getDeltaTime = function () {
  7020. return this.deltaTime;
  7021. };
  7022. Engine.prototype._measureFps = function () {
  7023. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7024. var length = this.previousFramesDuration.length;
  7025. if (length >= 2) {
  7026. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7027. }
  7028. if (length >= this.fpsRange) {
  7029. if (length > this.fpsRange) {
  7030. this.previousFramesDuration.splice(0, 1);
  7031. length = this.previousFramesDuration.length;
  7032. }
  7033. var sum = 0;
  7034. for (var id = 0; id < length - 1; id++) {
  7035. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7036. }
  7037. this.fps = 1000.0 / (sum / (length - 1));
  7038. }
  7039. };
  7040. // Statics
  7041. Engine.isSupported = function () {
  7042. try {
  7043. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7044. if (navigator.isCocoonJS) {
  7045. return true;
  7046. }
  7047. var tempcanvas = document.createElement("canvas");
  7048. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7049. return gl != null && !!window.WebGLRenderingContext;
  7050. }
  7051. catch (e) {
  7052. return false;
  7053. }
  7054. };
  7055. // Const statics
  7056. Engine._ALPHA_DISABLE = 0;
  7057. Engine._ALPHA_ADD = 1;
  7058. Engine._ALPHA_COMBINE = 2;
  7059. Engine._ALPHA_SUBTRACT = 3;
  7060. Engine._ALPHA_MULTIPLY = 4;
  7061. Engine._ALPHA_MAXIMIZED = 5;
  7062. Engine._ALPHA_ONEONE = 6;
  7063. Engine._DELAYLOADSTATE_NONE = 0;
  7064. Engine._DELAYLOADSTATE_LOADED = 1;
  7065. Engine._DELAYLOADSTATE_LOADING = 2;
  7066. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7067. Engine._TEXTUREFORMAT_ALPHA = 0;
  7068. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7069. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7070. Engine._TEXTUREFORMAT_RGB = 4;
  7071. Engine._TEXTUREFORMAT_RGBA = 5;
  7072. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7073. Engine._TEXTURETYPE_FLOAT = 1;
  7074. // Updatable statics so stick with vars here
  7075. Engine.Epsilon = 0.001;
  7076. Engine.CollisionsEpsilon = 0.001;
  7077. Engine.CodeRepository = "src/";
  7078. Engine.ShadersRepository = "src/Shaders/";
  7079. return Engine;
  7080. })();
  7081. BABYLON.Engine = Engine;
  7082. })(BABYLON || (BABYLON = {}));
  7083. var BABYLON;
  7084. (function (BABYLON) {
  7085. /**
  7086. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7087. */
  7088. var Node = (function () {
  7089. /**
  7090. * @constructor
  7091. * @param {string} name - the name and id to be given to this node
  7092. * @param {BABYLON.Scene} the scene this node will be added to
  7093. */
  7094. function Node(name, scene) {
  7095. this.state = "";
  7096. this.animations = new Array();
  7097. this._childrenFlag = -1;
  7098. this._isEnabled = true;
  7099. this._isReady = true;
  7100. this._currentRenderId = -1;
  7101. this._parentRenderId = -1;
  7102. this.name = name;
  7103. this.id = name;
  7104. this._scene = scene;
  7105. this._initCache();
  7106. }
  7107. Node.prototype.getScene = function () {
  7108. return this._scene;
  7109. };
  7110. Node.prototype.getEngine = function () {
  7111. return this._scene.getEngine();
  7112. };
  7113. // override it in derived class
  7114. Node.prototype.getWorldMatrix = function () {
  7115. return BABYLON.Matrix.Identity();
  7116. };
  7117. // override it in derived class if you add new variables to the cache
  7118. // and call the parent class method
  7119. Node.prototype._initCache = function () {
  7120. this._cache = {};
  7121. this._cache.parent = undefined;
  7122. };
  7123. Node.prototype.updateCache = function (force) {
  7124. if (!force && this.isSynchronized())
  7125. return;
  7126. this._cache.parent = this.parent;
  7127. this._updateCache();
  7128. };
  7129. // override it in derived class if you add new variables to the cache
  7130. // and call the parent class method if !ignoreParentClass
  7131. Node.prototype._updateCache = function (ignoreParentClass) {
  7132. };
  7133. // override it in derived class if you add new variables to the cache
  7134. Node.prototype._isSynchronized = function () {
  7135. return true;
  7136. };
  7137. Node.prototype._markSyncedWithParent = function () {
  7138. this._parentRenderId = this.parent._currentRenderId;
  7139. };
  7140. Node.prototype.isSynchronizedWithParent = function () {
  7141. if (!this.parent) {
  7142. return true;
  7143. }
  7144. if (this._parentRenderId !== this.parent._currentRenderId) {
  7145. return false;
  7146. }
  7147. return this.parent.isSynchronized();
  7148. };
  7149. Node.prototype.isSynchronized = function (updateCache) {
  7150. var check = this.hasNewParent();
  7151. check = check || !this.isSynchronizedWithParent();
  7152. check = check || !this._isSynchronized();
  7153. if (updateCache)
  7154. this.updateCache(true);
  7155. return !check;
  7156. };
  7157. Node.prototype.hasNewParent = function (update) {
  7158. if (this._cache.parent === this.parent)
  7159. return false;
  7160. if (update)
  7161. this._cache.parent = this.parent;
  7162. return true;
  7163. };
  7164. /**
  7165. * Is this node ready to be used/rendered
  7166. * @return {boolean} is it ready
  7167. */
  7168. Node.prototype.isReady = function () {
  7169. return this._isReady;
  7170. };
  7171. /**
  7172. * Is this node enabled.
  7173. * If the node has a parent and is enabled, the parent will be inspected as well.
  7174. * @return {boolean} whether this node (and its parent) is enabled.
  7175. * @see setEnabled
  7176. */
  7177. Node.prototype.isEnabled = function () {
  7178. if (!this._isEnabled) {
  7179. return false;
  7180. }
  7181. if (this.parent) {
  7182. return this.parent.isEnabled();
  7183. }
  7184. return true;
  7185. };
  7186. /**
  7187. * Set the enabled state of this node.
  7188. * @param {boolean} value - the new enabled state
  7189. * @see isEnabled
  7190. */
  7191. Node.prototype.setEnabled = function (value) {
  7192. this._isEnabled = value;
  7193. };
  7194. /**
  7195. * Is this node a descendant of the given node.
  7196. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7197. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7198. * @see parent
  7199. */
  7200. Node.prototype.isDescendantOf = function (ancestor) {
  7201. if (this.parent) {
  7202. if (this.parent === ancestor) {
  7203. return true;
  7204. }
  7205. return this.parent.isDescendantOf(ancestor);
  7206. }
  7207. return false;
  7208. };
  7209. Node.prototype._getDescendants = function (list, results) {
  7210. for (var index = 0; index < list.length; index++) {
  7211. var item = list[index];
  7212. if (item.isDescendantOf(this)) {
  7213. results.push(item);
  7214. }
  7215. }
  7216. };
  7217. /**
  7218. * Will return all nodes that have this node as parent.
  7219. * @return {BABYLON.Node[]} all children nodes of all types.
  7220. */
  7221. Node.prototype.getDescendants = function () {
  7222. var results = [];
  7223. this._getDescendants(this._scene.meshes, results);
  7224. this._getDescendants(this._scene.lights, results);
  7225. this._getDescendants(this._scene.cameras, results);
  7226. return results;
  7227. };
  7228. Node.prototype._setReady = function (state) {
  7229. if (state == this._isReady) {
  7230. return;
  7231. }
  7232. if (!state) {
  7233. this._isReady = false;
  7234. return;
  7235. }
  7236. this._isReady = true;
  7237. if (this.onReady) {
  7238. this.onReady(this);
  7239. }
  7240. };
  7241. return Node;
  7242. })();
  7243. BABYLON.Node = Node;
  7244. })(BABYLON || (BABYLON = {}));
  7245. var BABYLON;
  7246. (function (BABYLON) {
  7247. var FilesInput = (function () {
  7248. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7249. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7250. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7251. this._engine = p_engine;
  7252. this._canvas = p_canvas;
  7253. this._currentScene = p_scene;
  7254. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7255. this._progressCallback = p_progressCallback;
  7256. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7257. this._textureLoadingCallback = p_textureLoadingCallback;
  7258. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7259. }
  7260. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7261. var _this = this;
  7262. if (p_elementToMonitor) {
  7263. this._elementToMonitor = p_elementToMonitor;
  7264. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7265. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7266. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7267. }
  7268. };
  7269. FilesInput.prototype.renderFunction = function () {
  7270. if (this._additionnalRenderLoopLogicCallback) {
  7271. this._additionnalRenderLoopLogicCallback();
  7272. }
  7273. if (this._currentScene) {
  7274. if (this._textureLoadingCallback) {
  7275. var remaining = this._currentScene.getWaitingItemsCount();
  7276. if (remaining > 0) {
  7277. this._textureLoadingCallback(remaining);
  7278. }
  7279. }
  7280. this._currentScene.render();
  7281. }
  7282. };
  7283. FilesInput.prototype.drag = function (e) {
  7284. e.stopPropagation();
  7285. e.preventDefault();
  7286. };
  7287. FilesInput.prototype.drop = function (eventDrop) {
  7288. eventDrop.stopPropagation();
  7289. eventDrop.preventDefault();
  7290. this.loadFiles(eventDrop);
  7291. };
  7292. FilesInput.prototype.loadFiles = function (event) {
  7293. if (this._startingProcessingFilesCallback)
  7294. this._startingProcessingFilesCallback();
  7295. // Handling data transfer via drag'n'drop
  7296. if (event && event.dataTransfer && event.dataTransfer.files) {
  7297. this._filesToLoad = event.dataTransfer.files;
  7298. }
  7299. // Handling files from input files
  7300. if (event && event.target && event.target.files) {
  7301. this._filesToLoad = event.target.files;
  7302. }
  7303. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7304. for (var i = 0; i < this._filesToLoad.length; i++) {
  7305. switch (this._filesToLoad[i].type) {
  7306. case "image/jpeg":
  7307. case "image/png":
  7308. case "image/bmp":
  7309. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7310. break;
  7311. case "image/targa":
  7312. case "image/vnd.ms-dds":
  7313. case "audio/wav":
  7314. case "audio/x-wav":
  7315. case "audio/mp3":
  7316. case "audio/mpeg":
  7317. case "audio/mpeg3":
  7318. case "audio/x-mpeg-3":
  7319. case "audio/ogg":
  7320. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7321. break;
  7322. default:
  7323. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7324. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7325. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7326. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7327. this._sceneFileToLoad = this._filesToLoad[i];
  7328. }
  7329. break;
  7330. }
  7331. }
  7332. this.reload();
  7333. }
  7334. };
  7335. FilesInput.prototype.reload = function () {
  7336. var _this = this;
  7337. var that = this;
  7338. // If a ".babylon" file has been provided
  7339. if (this._sceneFileToLoad) {
  7340. if (this._currentScene) {
  7341. if (BABYLON.Tools.errorsCount > 0) {
  7342. BABYLON.Tools.ClearLogCache();
  7343. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7344. }
  7345. this._engine.stopRenderLoop();
  7346. this._currentScene.dispose();
  7347. }
  7348. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7349. that._currentScene = newScene;
  7350. // Wait for textures and shaders to be ready
  7351. that._currentScene.executeWhenReady(function () {
  7352. // Attach camera to canvas inputs
  7353. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7354. that._currentScene.createDefaultCameraOrLight();
  7355. }
  7356. that._currentScene.activeCamera.attachControl(that._canvas);
  7357. if (that._sceneLoadedCallback) {
  7358. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7359. }
  7360. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7361. });
  7362. }, function (progress) {
  7363. if (_this._progressCallback) {
  7364. _this._progressCallback(progress);
  7365. }
  7366. });
  7367. }
  7368. else {
  7369. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7370. }
  7371. };
  7372. FilesInput.FilesTextures = new Array();
  7373. FilesInput.FilesToLoad = new Array();
  7374. return FilesInput;
  7375. })();
  7376. BABYLON.FilesInput = FilesInput;
  7377. })(BABYLON || (BABYLON = {}));
  7378. var BABYLON;
  7379. (function (BABYLON) {
  7380. var IntersectionInfo = (function () {
  7381. function IntersectionInfo(bu, bv, distance) {
  7382. this.bu = bu;
  7383. this.bv = bv;
  7384. this.distance = distance;
  7385. this.faceId = 0;
  7386. this.subMeshId = 0;
  7387. }
  7388. return IntersectionInfo;
  7389. })();
  7390. BABYLON.IntersectionInfo = IntersectionInfo;
  7391. var PickingInfo = (function () {
  7392. function PickingInfo() {
  7393. this.hit = false;
  7394. this.distance = 0;
  7395. this.pickedPoint = null;
  7396. this.pickedMesh = null;
  7397. this.bu = 0;
  7398. this.bv = 0;
  7399. this.faceId = -1;
  7400. this.subMeshId = 0;
  7401. }
  7402. // Methods
  7403. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7404. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7405. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7406. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7407. return null;
  7408. }
  7409. var indices = this.pickedMesh.getIndices();
  7410. var result;
  7411. if (useVerticesNormals) {
  7412. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7413. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7414. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7415. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7416. normal0 = normal0.scale(this.bu);
  7417. normal1 = normal1.scale(this.bv);
  7418. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7419. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7420. }
  7421. else {
  7422. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7423. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7424. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7425. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7426. var p1p2 = vertex1.subtract(vertex2);
  7427. var p3p2 = vertex3.subtract(vertex2);
  7428. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7429. }
  7430. if (useWorldCoordinates) {
  7431. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7432. }
  7433. return BABYLON.Vector3.Normalize(result);
  7434. };
  7435. PickingInfo.prototype.getTextureCoordinates = function () {
  7436. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7437. return null;
  7438. }
  7439. var indices = this.pickedMesh.getIndices();
  7440. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7441. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7442. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7443. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7444. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7445. uv1 = uv1.scale(this.bu);
  7446. uv2 = uv2.scale(this.bv);
  7447. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7448. };
  7449. return PickingInfo;
  7450. })();
  7451. BABYLON.PickingInfo = PickingInfo;
  7452. })(BABYLON || (BABYLON = {}));
  7453. var BABYLON;
  7454. (function (BABYLON) {
  7455. var BoundingSphere = (function () {
  7456. function BoundingSphere(minimum, maximum) {
  7457. this.minimum = minimum;
  7458. this.maximum = maximum;
  7459. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7460. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7461. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7462. this.radius = distance * 0.5;
  7463. this.centerWorld = BABYLON.Vector3.Zero();
  7464. this._update(BABYLON.Matrix.Identity());
  7465. }
  7466. // Methods
  7467. BoundingSphere.prototype._update = function (world) {
  7468. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7469. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7470. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7471. };
  7472. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7473. for (var i = 0; i < 6; i++) {
  7474. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7475. return false;
  7476. }
  7477. return true;
  7478. };
  7479. BoundingSphere.prototype.intersectsPoint = function (point) {
  7480. var x = this.centerWorld.x - point.x;
  7481. var y = this.centerWorld.y - point.y;
  7482. var z = this.centerWorld.z - point.z;
  7483. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7484. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7485. return false;
  7486. return true;
  7487. };
  7488. // Statics
  7489. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7490. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7491. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7492. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7493. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7494. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7495. return false;
  7496. return true;
  7497. };
  7498. return BoundingSphere;
  7499. })();
  7500. BABYLON.BoundingSphere = BoundingSphere;
  7501. })(BABYLON || (BABYLON = {}));
  7502. var BABYLON;
  7503. (function (BABYLON) {
  7504. var BoundingBox = (function () {
  7505. function BoundingBox(minimum, maximum) {
  7506. this.minimum = minimum;
  7507. this.maximum = maximum;
  7508. this.vectors = new Array();
  7509. this.vectorsWorld = new Array();
  7510. // Bounding vectors
  7511. this.vectors.push(this.minimum.clone());
  7512. this.vectors.push(this.maximum.clone());
  7513. this.vectors.push(this.minimum.clone());
  7514. this.vectors[2].x = this.maximum.x;
  7515. this.vectors.push(this.minimum.clone());
  7516. this.vectors[3].y = this.maximum.y;
  7517. this.vectors.push(this.minimum.clone());
  7518. this.vectors[4].z = this.maximum.z;
  7519. this.vectors.push(this.maximum.clone());
  7520. this.vectors[5].z = this.minimum.z;
  7521. this.vectors.push(this.maximum.clone());
  7522. this.vectors[6].x = this.minimum.x;
  7523. this.vectors.push(this.maximum.clone());
  7524. this.vectors[7].y = this.minimum.y;
  7525. // OBB
  7526. this.center = this.maximum.add(this.minimum).scale(0.5);
  7527. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7528. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7529. // World
  7530. for (var index = 0; index < this.vectors.length; index++) {
  7531. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7532. }
  7533. this.minimumWorld = BABYLON.Vector3.Zero();
  7534. this.maximumWorld = BABYLON.Vector3.Zero();
  7535. this._update(BABYLON.Matrix.Identity());
  7536. }
  7537. // Methods
  7538. BoundingBox.prototype.getWorldMatrix = function () {
  7539. return this._worldMatrix;
  7540. };
  7541. BoundingBox.prototype._update = function (world) {
  7542. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7543. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7544. for (var index = 0; index < this.vectors.length; index++) {
  7545. var v = this.vectorsWorld[index];
  7546. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7547. if (v.x < this.minimumWorld.x)
  7548. this.minimumWorld.x = v.x;
  7549. if (v.y < this.minimumWorld.y)
  7550. this.minimumWorld.y = v.y;
  7551. if (v.z < this.minimumWorld.z)
  7552. this.minimumWorld.z = v.z;
  7553. if (v.x > this.maximumWorld.x)
  7554. this.maximumWorld.x = v.x;
  7555. if (v.y > this.maximumWorld.y)
  7556. this.maximumWorld.y = v.y;
  7557. if (v.z > this.maximumWorld.z)
  7558. this.maximumWorld.z = v.z;
  7559. }
  7560. // OBB
  7561. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7562. this.center.scaleInPlace(0.5);
  7563. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7564. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7565. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7566. this._worldMatrix = world;
  7567. };
  7568. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7569. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7570. };
  7571. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7572. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7573. };
  7574. BoundingBox.prototype.intersectsPoint = function (point) {
  7575. var delta = -BABYLON.Engine.Epsilon;
  7576. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7577. return false;
  7578. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7579. return false;
  7580. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7581. return false;
  7582. return true;
  7583. };
  7584. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7585. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7586. };
  7587. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7588. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7589. return false;
  7590. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7591. return false;
  7592. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7593. return false;
  7594. return true;
  7595. };
  7596. // Statics
  7597. BoundingBox.Intersects = function (box0, box1) {
  7598. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7599. return false;
  7600. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7601. return false;
  7602. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7603. return false;
  7604. return true;
  7605. };
  7606. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7607. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7608. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7609. return (num <= (sphereRadius * sphereRadius));
  7610. };
  7611. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7612. for (var p = 0; p < 6; p++) {
  7613. for (var i = 0; i < 8; i++) {
  7614. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7615. return false;
  7616. }
  7617. }
  7618. }
  7619. return true;
  7620. };
  7621. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7622. for (var p = 0; p < 6; p++) {
  7623. var inCount = 8;
  7624. for (var i = 0; i < 8; i++) {
  7625. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7626. --inCount;
  7627. }
  7628. else {
  7629. break;
  7630. }
  7631. }
  7632. if (inCount === 0)
  7633. return false;
  7634. }
  7635. return true;
  7636. };
  7637. return BoundingBox;
  7638. })();
  7639. BABYLON.BoundingBox = BoundingBox;
  7640. })(BABYLON || (BABYLON = {}));
  7641. var BABYLON;
  7642. (function (BABYLON) {
  7643. var computeBoxExtents = function (axis, box) {
  7644. var p = BABYLON.Vector3.Dot(box.center, axis);
  7645. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7646. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7647. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7648. var r = r0 + r1 + r2;
  7649. return {
  7650. min: p - r,
  7651. max: p + r
  7652. };
  7653. };
  7654. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7655. var axisOverlap = function (axis, box0, box1) {
  7656. var result0 = computeBoxExtents(axis, box0);
  7657. var result1 = computeBoxExtents(axis, box1);
  7658. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7659. };
  7660. var BoundingInfo = (function () {
  7661. function BoundingInfo(minimum, maximum) {
  7662. this.minimum = minimum;
  7663. this.maximum = maximum;
  7664. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7665. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7666. }
  7667. // Methods
  7668. BoundingInfo.prototype._update = function (world) {
  7669. this.boundingBox._update(world);
  7670. this.boundingSphere._update(world);
  7671. };
  7672. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7673. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7674. return false;
  7675. return this.boundingBox.isInFrustum(frustumPlanes);
  7676. };
  7677. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7678. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7679. };
  7680. BoundingInfo.prototype._checkCollision = function (collider) {
  7681. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7682. };
  7683. BoundingInfo.prototype.intersectsPoint = function (point) {
  7684. if (!this.boundingSphere.centerWorld) {
  7685. return false;
  7686. }
  7687. if (!this.boundingSphere.intersectsPoint(point)) {
  7688. return false;
  7689. }
  7690. if (!this.boundingBox.intersectsPoint(point)) {
  7691. return false;
  7692. }
  7693. return true;
  7694. };
  7695. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7696. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7697. return false;
  7698. }
  7699. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7700. return false;
  7701. }
  7702. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7703. return false;
  7704. }
  7705. if (!precise) {
  7706. return true;
  7707. }
  7708. var box0 = this.boundingBox;
  7709. var box1 = boundingInfo.boundingBox;
  7710. if (!axisOverlap(box0.directions[0], box0, box1))
  7711. return false;
  7712. if (!axisOverlap(box0.directions[1], box0, box1))
  7713. return false;
  7714. if (!axisOverlap(box0.directions[2], box0, box1))
  7715. return false;
  7716. if (!axisOverlap(box1.directions[0], box0, box1))
  7717. return false;
  7718. if (!axisOverlap(box1.directions[1], box0, box1))
  7719. return false;
  7720. if (!axisOverlap(box1.directions[2], box0, box1))
  7721. return false;
  7722. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7723. return false;
  7724. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7725. return false;
  7726. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7727. return false;
  7728. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7729. return false;
  7730. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7731. return false;
  7732. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7733. return false;
  7734. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7735. return false;
  7736. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7737. return false;
  7738. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7739. return false;
  7740. return true;
  7741. };
  7742. return BoundingInfo;
  7743. })();
  7744. BABYLON.BoundingInfo = BoundingInfo;
  7745. })(BABYLON || (BABYLON = {}));
  7746. var BABYLON;
  7747. (function (BABYLON) {
  7748. var AbstractMesh = (function (_super) {
  7749. __extends(AbstractMesh, _super);
  7750. function AbstractMesh(name, scene) {
  7751. var _this = this;
  7752. _super.call(this, name, scene);
  7753. // Properties
  7754. this.definedFacingForward = true; // orientation for POV movement & rotation
  7755. this.position = new BABYLON.Vector3(0, 0, 0);
  7756. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7757. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7758. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7759. this.visibility = 1.0;
  7760. this.alphaIndex = Number.MAX_VALUE;
  7761. this.infiniteDistance = false;
  7762. this.isVisible = true;
  7763. this.isPickable = true;
  7764. this.showBoundingBox = false;
  7765. this.showSubMeshesBoundingBox = false;
  7766. this.onDispose = null;
  7767. this.isBlocker = false;
  7768. this.renderingGroupId = 0;
  7769. this.receiveShadows = false;
  7770. this.renderOutline = false;
  7771. this.outlineColor = BABYLON.Color3.Red();
  7772. this.outlineWidth = 0.02;
  7773. this.renderOverlay = false;
  7774. this.overlayColor = BABYLON.Color3.Red();
  7775. this.overlayAlpha = 0.5;
  7776. this.hasVertexAlpha = false;
  7777. this.useVertexColors = true;
  7778. this.applyFog = true;
  7779. this.computeBonesUsingShaders = true;
  7780. this.useOctreeForRenderingSelection = true;
  7781. this.useOctreeForPicking = true;
  7782. this.useOctreeForCollisions = true;
  7783. this.layerMask = 0x0FFFFFFF;
  7784. this.alwaysSelectAsActiveMesh = false;
  7785. // Physics
  7786. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7787. // Collisions
  7788. this._checkCollisions = false;
  7789. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7790. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7791. this._collider = new BABYLON.Collider();
  7792. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7793. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7794. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7795. // Edges
  7796. this.edgesWidth = 1;
  7797. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7798. // Cache
  7799. this._localScaling = BABYLON.Matrix.Zero();
  7800. this._localRotation = BABYLON.Matrix.Zero();
  7801. this._localTranslation = BABYLON.Matrix.Zero();
  7802. this._localBillboard = BABYLON.Matrix.Zero();
  7803. this._localPivotScaling = BABYLON.Matrix.Zero();
  7804. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7805. this._localWorld = BABYLON.Matrix.Zero();
  7806. this._worldMatrix = BABYLON.Matrix.Zero();
  7807. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7808. this._absolutePosition = BABYLON.Vector3.Zero();
  7809. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7810. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7811. this._isDirty = false;
  7812. this._pivotMatrix = BABYLON.Matrix.Identity();
  7813. this._isDisposed = false;
  7814. this._renderId = 0;
  7815. this._intersectionsInProgress = new Array();
  7816. this._onAfterWorldMatrixUpdate = new Array();
  7817. this._isWorldMatrixFrozen = false;
  7818. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7819. if (collidedMesh === void 0) { collidedMesh = null; }
  7820. //TODO move this to the collision coordinator!
  7821. if (_this.getScene().workerCollisions)
  7822. newPosition.multiplyInPlace(_this._collider.radius);
  7823. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7824. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7825. _this.position.addInPlace(_this._diffPositionForCollisions);
  7826. }
  7827. if (_this.onCollide && collidedMesh) {
  7828. _this.onCollide(collidedMesh);
  7829. }
  7830. };
  7831. scene.addMesh(this);
  7832. }
  7833. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7834. get: function () {
  7835. return AbstractMesh._BILLBOARDMODE_NONE;
  7836. },
  7837. enumerable: true,
  7838. configurable: true
  7839. });
  7840. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7841. get: function () {
  7842. return AbstractMesh._BILLBOARDMODE_X;
  7843. },
  7844. enumerable: true,
  7845. configurable: true
  7846. });
  7847. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7848. get: function () {
  7849. return AbstractMesh._BILLBOARDMODE_Y;
  7850. },
  7851. enumerable: true,
  7852. configurable: true
  7853. });
  7854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7855. get: function () {
  7856. return AbstractMesh._BILLBOARDMODE_Z;
  7857. },
  7858. enumerable: true,
  7859. configurable: true
  7860. });
  7861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7862. get: function () {
  7863. return AbstractMesh._BILLBOARDMODE_ALL;
  7864. },
  7865. enumerable: true,
  7866. configurable: true
  7867. });
  7868. // Methods
  7869. AbstractMesh.prototype.disableEdgesRendering = function () {
  7870. if (this._edgesRenderer !== undefined) {
  7871. this._edgesRenderer.dispose();
  7872. this._edgesRenderer = undefined;
  7873. }
  7874. };
  7875. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7876. if (epsilon === void 0) { epsilon = 0.95; }
  7877. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7878. this.disableEdgesRendering();
  7879. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7880. };
  7881. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7882. get: function () {
  7883. return false;
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. AbstractMesh.prototype.getLOD = function (camera) {
  7889. return this;
  7890. };
  7891. AbstractMesh.prototype.getTotalVertices = function () {
  7892. return 0;
  7893. };
  7894. AbstractMesh.prototype.getIndices = function () {
  7895. return null;
  7896. };
  7897. AbstractMesh.prototype.getVerticesData = function (kind) {
  7898. return null;
  7899. };
  7900. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7901. return false;
  7902. };
  7903. AbstractMesh.prototype.getBoundingInfo = function () {
  7904. if (this._masterMesh) {
  7905. return this._masterMesh.getBoundingInfo();
  7906. }
  7907. if (!this._boundingInfo) {
  7908. this._updateBoundingInfo();
  7909. }
  7910. return this._boundingInfo;
  7911. };
  7912. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7913. get: function () {
  7914. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. AbstractMesh.prototype._preActivate = function () {
  7920. };
  7921. AbstractMesh.prototype._activate = function (renderId) {
  7922. this._renderId = renderId;
  7923. };
  7924. AbstractMesh.prototype.getWorldMatrix = function () {
  7925. if (this._masterMesh) {
  7926. return this._masterMesh.getWorldMatrix();
  7927. }
  7928. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7929. this.computeWorldMatrix();
  7930. }
  7931. return this._worldMatrix;
  7932. };
  7933. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7934. get: function () {
  7935. return this._worldMatrix;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7941. get: function () {
  7942. return this._absolutePosition;
  7943. },
  7944. enumerable: true,
  7945. configurable: true
  7946. });
  7947. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7948. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7949. this.computeWorldMatrix(true);
  7950. this._isWorldMatrixFrozen = true;
  7951. };
  7952. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7953. this._isWorldMatrixFrozen = false;
  7954. this.computeWorldMatrix(true);
  7955. };
  7956. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7957. get: function () {
  7958. return this._isWorldMatrixFrozen;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7964. axis.normalize();
  7965. if (!this.rotationQuaternion) {
  7966. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7967. this.rotation = BABYLON.Vector3.Zero();
  7968. }
  7969. if (!space || space === BABYLON.Space.LOCAL) {
  7970. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7971. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7972. }
  7973. else {
  7974. if (this.parent) {
  7975. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7976. invertParentWorldMatrix.invert();
  7977. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7978. }
  7979. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7980. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7981. }
  7982. };
  7983. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7984. var displacementVector = axis.scale(distance);
  7985. if (!space || space === BABYLON.Space.LOCAL) {
  7986. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7987. this.setPositionWithLocalVector(tempV3);
  7988. }
  7989. else {
  7990. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7991. }
  7992. };
  7993. AbstractMesh.prototype.getAbsolutePosition = function () {
  7994. this.computeWorldMatrix();
  7995. return this._absolutePosition;
  7996. };
  7997. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7998. if (!absolutePosition) {
  7999. return;
  8000. }
  8001. var absolutePositionX;
  8002. var absolutePositionY;
  8003. var absolutePositionZ;
  8004. if (absolutePosition.x === undefined) {
  8005. if (arguments.length < 3) {
  8006. return;
  8007. }
  8008. absolutePositionX = arguments[0];
  8009. absolutePositionY = arguments[1];
  8010. absolutePositionZ = arguments[2];
  8011. }
  8012. else {
  8013. absolutePositionX = absolutePosition.x;
  8014. absolutePositionY = absolutePosition.y;
  8015. absolutePositionZ = absolutePosition.z;
  8016. }
  8017. if (this.parent) {
  8018. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8019. invertParentWorldMatrix.invert();
  8020. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8021. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8022. }
  8023. else {
  8024. this.position.x = absolutePositionX;
  8025. this.position.y = absolutePositionY;
  8026. this.position.z = absolutePositionZ;
  8027. }
  8028. };
  8029. // ================================== Point of View Movement =================================
  8030. /**
  8031. * Perform relative position change from the point of view of behind the front of the mesh.
  8032. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8033. * Supports definition of mesh facing forward or backward.
  8034. * @param {number} amountRight
  8035. * @param {number} amountUp
  8036. * @param {number} amountForward
  8037. */
  8038. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8039. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8040. };
  8041. /**
  8042. * Calculate relative position change from the point of view of behind the front of the mesh.
  8043. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8044. * Supports definition of mesh facing forward or backward.
  8045. * @param {number} amountRight
  8046. * @param {number} amountUp
  8047. * @param {number} amountForward
  8048. */
  8049. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8050. var rotMatrix = new BABYLON.Matrix();
  8051. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8052. rotQuaternion.toRotationMatrix(rotMatrix);
  8053. var translationDelta = BABYLON.Vector3.Zero();
  8054. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8055. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8056. return translationDelta;
  8057. };
  8058. // ================================== Point of View Rotation =================================
  8059. /**
  8060. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8061. * Supports definition of mesh facing forward or backward.
  8062. * @param {number} flipBack
  8063. * @param {number} twirlClockwise
  8064. * @param {number} tiltRight
  8065. */
  8066. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8067. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8068. };
  8069. /**
  8070. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8071. * Supports definition of mesh facing forward or backward.
  8072. * @param {number} flipBack
  8073. * @param {number} twirlClockwise
  8074. * @param {number} tiltRight
  8075. */
  8076. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8077. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8078. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8079. };
  8080. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8081. this._pivotMatrix = matrix;
  8082. this._cache.pivotMatrixUpdated = true;
  8083. };
  8084. AbstractMesh.prototype.getPivotMatrix = function () {
  8085. return this._pivotMatrix;
  8086. };
  8087. AbstractMesh.prototype._isSynchronized = function () {
  8088. if (this._isDirty) {
  8089. return false;
  8090. }
  8091. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8092. return false;
  8093. if (this._cache.pivotMatrixUpdated) {
  8094. return false;
  8095. }
  8096. if (this.infiniteDistance) {
  8097. return false;
  8098. }
  8099. if (!this._cache.position.equals(this.position))
  8100. return false;
  8101. if (this.rotationQuaternion) {
  8102. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8103. return false;
  8104. }
  8105. else {
  8106. if (!this._cache.rotation.equals(this.rotation))
  8107. return false;
  8108. }
  8109. if (!this._cache.scaling.equals(this.scaling))
  8110. return false;
  8111. return true;
  8112. };
  8113. AbstractMesh.prototype._initCache = function () {
  8114. _super.prototype._initCache.call(this);
  8115. this._cache.localMatrixUpdated = false;
  8116. this._cache.position = BABYLON.Vector3.Zero();
  8117. this._cache.scaling = BABYLON.Vector3.Zero();
  8118. this._cache.rotation = BABYLON.Vector3.Zero();
  8119. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8120. };
  8121. AbstractMesh.prototype.markAsDirty = function (property) {
  8122. if (property === "rotation") {
  8123. this.rotationQuaternion = null;
  8124. }
  8125. this._currentRenderId = Number.MAX_VALUE;
  8126. this._isDirty = true;
  8127. };
  8128. AbstractMesh.prototype._updateBoundingInfo = function () {
  8129. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8130. this._boundingInfo._update(this.worldMatrixFromCache);
  8131. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8132. };
  8133. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8134. if (!this.subMeshes) {
  8135. return;
  8136. }
  8137. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8138. var subMesh = this.subMeshes[subIndex];
  8139. subMesh.updateBoundingInfo(matrix);
  8140. }
  8141. };
  8142. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8143. if (this._isWorldMatrixFrozen) {
  8144. return this._worldMatrix;
  8145. }
  8146. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8147. return this._worldMatrix;
  8148. }
  8149. this._cache.position.copyFrom(this.position);
  8150. this._cache.scaling.copyFrom(this.scaling);
  8151. this._cache.pivotMatrixUpdated = false;
  8152. this._currentRenderId = this.getScene().getRenderId();
  8153. this._isDirty = false;
  8154. // Scaling
  8155. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8156. // Rotation
  8157. if (this.rotationQuaternion) {
  8158. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8159. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8160. }
  8161. else {
  8162. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8163. this._cache.rotation.copyFrom(this.rotation);
  8164. }
  8165. // Translation
  8166. if (this.infiniteDistance && !this.parent) {
  8167. var camera = this.getScene().activeCamera;
  8168. if (camera) {
  8169. var cameraWorldMatrix = camera.getWorldMatrix();
  8170. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8171. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8172. }
  8173. }
  8174. else {
  8175. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8176. }
  8177. // Composing transformations
  8178. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8179. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8180. // Billboarding
  8181. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8182. var localPosition = this.position.clone();
  8183. var zero = this.getScene().activeCamera.globalPosition.clone();
  8184. if (this.parent && this.parent.position) {
  8185. localPosition.addInPlace(this.parent.position);
  8186. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8187. }
  8188. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8189. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8190. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8191. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8192. zero.y = localPosition.y + 0.001;
  8193. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8194. zero.z = localPosition.z + 0.001;
  8195. }
  8196. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8197. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8198. this._localBillboard.invert();
  8199. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8200. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8201. }
  8202. // Local world
  8203. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8204. // Parent
  8205. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8206. this._markSyncedWithParent();
  8207. if (this._meshToBoneReferal) {
  8208. if (!this._localMeshReferalTransform) {
  8209. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8210. }
  8211. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8212. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8213. }
  8214. else {
  8215. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8216. }
  8217. }
  8218. else {
  8219. this._worldMatrix.copyFrom(this._localWorld);
  8220. }
  8221. // Bounding info
  8222. this._updateBoundingInfo();
  8223. // Absolute position
  8224. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8225. // Callbacks
  8226. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8227. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8228. }
  8229. return this._worldMatrix;
  8230. };
  8231. /**
  8232. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8233. * @param func: callback function to add
  8234. */
  8235. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8236. this._onAfterWorldMatrixUpdate.push(func);
  8237. };
  8238. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8239. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8240. if (index > -1) {
  8241. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8242. }
  8243. };
  8244. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8245. this.computeWorldMatrix();
  8246. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8247. };
  8248. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8249. this.computeWorldMatrix();
  8250. var invLocalWorldMatrix = this._localWorld.clone();
  8251. invLocalWorldMatrix.invert();
  8252. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8253. };
  8254. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8255. this.computeWorldMatrix(true);
  8256. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8257. };
  8258. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8259. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8260. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8261. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8262. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8263. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8264. /// <returns>Mesh oriented towards targetMesh</returns>
  8265. yawCor = yawCor || 0; // default to zero if undefined
  8266. pitchCor = pitchCor || 0;
  8267. rollCor = rollCor || 0;
  8268. var dv = targetPoint.subtract(this.position);
  8269. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8270. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8271. var pitch = Math.atan2(dv.y, len);
  8272. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8273. };
  8274. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8275. this._meshToBoneReferal = affectedMesh;
  8276. this.parent = bone;
  8277. };
  8278. AbstractMesh.prototype.detachFromBone = function () {
  8279. this._meshToBoneReferal = null;
  8280. this.parent = null;
  8281. };
  8282. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8283. return this._boundingInfo.isInFrustum(frustumPlanes);
  8284. };
  8285. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8286. if (!camera) {
  8287. camera = this.getScene().activeCamera;
  8288. }
  8289. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8290. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8291. return false;
  8292. }
  8293. return true;
  8294. };
  8295. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8296. if (!this._boundingInfo || !mesh._boundingInfo) {
  8297. return false;
  8298. }
  8299. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8300. };
  8301. AbstractMesh.prototype.intersectsPoint = function (point) {
  8302. if (!this._boundingInfo) {
  8303. return false;
  8304. }
  8305. return this._boundingInfo.intersectsPoint(point);
  8306. };
  8307. // Physics
  8308. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8309. var physicsEngine = this.getScene().getPhysicsEngine();
  8310. if (!physicsEngine) {
  8311. return;
  8312. }
  8313. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8314. if (impostor.impostor) {
  8315. // Old API
  8316. options = impostor;
  8317. impostor = impostor.impostor;
  8318. }
  8319. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8320. physicsEngine._unregisterMesh(this);
  8321. return;
  8322. }
  8323. if (!options) {
  8324. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8325. }
  8326. else {
  8327. if (!options.mass && options.mass !== 0)
  8328. options.mass = 0;
  8329. if (!options.friction && options.friction !== 0)
  8330. options.friction = 0.2;
  8331. if (!options.restitution && options.restitution !== 0)
  8332. options.restitution = 0.2;
  8333. }
  8334. this._physicImpostor = impostor;
  8335. this._physicsMass = options.mass;
  8336. this._physicsFriction = options.friction;
  8337. this._physicRestitution = options.restitution;
  8338. return physicsEngine._registerMesh(this, impostor, options);
  8339. };
  8340. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8341. if (!this._physicImpostor) {
  8342. return BABYLON.PhysicsEngine.NoImpostor;
  8343. }
  8344. return this._physicImpostor;
  8345. };
  8346. AbstractMesh.prototype.getPhysicsMass = function () {
  8347. if (!this._physicsMass) {
  8348. return 0;
  8349. }
  8350. return this._physicsMass;
  8351. };
  8352. AbstractMesh.prototype.getPhysicsFriction = function () {
  8353. if (!this._physicsFriction) {
  8354. return 0;
  8355. }
  8356. return this._physicsFriction;
  8357. };
  8358. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8359. if (!this._physicRestitution) {
  8360. return 0;
  8361. }
  8362. return this._physicRestitution;
  8363. };
  8364. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8365. if (!camera) {
  8366. camera = this.getScene().activeCamera;
  8367. }
  8368. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8369. };
  8370. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8371. if (!camera) {
  8372. camera = this.getScene().activeCamera;
  8373. }
  8374. return this.absolutePosition.subtract(camera.position).length();
  8375. };
  8376. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8377. if (!this._physicImpostor) {
  8378. return;
  8379. }
  8380. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8381. };
  8382. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8383. if (!this._physicImpostor) {
  8384. return;
  8385. }
  8386. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8387. };
  8388. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8389. if (!this._physicImpostor) {
  8390. return;
  8391. }
  8392. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8393. };
  8394. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8395. // Collisions
  8396. get: function () {
  8397. return this._checkCollisions;
  8398. },
  8399. set: function (collisionEnabled) {
  8400. this._checkCollisions = collisionEnabled;
  8401. if (this.getScene().workerCollisions) {
  8402. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8403. }
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8409. var globalPosition = this.getAbsolutePosition();
  8410. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8411. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8412. this._collider.radius = this.ellipsoid;
  8413. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8414. };
  8415. // Submeshes octree
  8416. /**
  8417. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8418. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8419. */
  8420. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8421. if (maxCapacity === void 0) { maxCapacity = 64; }
  8422. if (maxDepth === void 0) { maxDepth = 2; }
  8423. if (!this._submeshesOctree) {
  8424. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8425. }
  8426. this.computeWorldMatrix(true);
  8427. // Update octree
  8428. var bbox = this.getBoundingInfo().boundingBox;
  8429. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8430. return this._submeshesOctree;
  8431. };
  8432. // Collisions
  8433. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8434. this._generatePointsArray();
  8435. // Transformation
  8436. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8437. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8438. subMesh._lastColliderWorldVertices = [];
  8439. subMesh._trianglePlanes = [];
  8440. var start = subMesh.verticesStart;
  8441. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8442. for (var i = start; i < end; i++) {
  8443. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8444. }
  8445. }
  8446. // Collide
  8447. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8448. if (collider.collisionFound) {
  8449. collider.collidedMesh = this;
  8450. }
  8451. };
  8452. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8453. var subMeshes;
  8454. var len;
  8455. // Octrees
  8456. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8457. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8458. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8459. len = intersections.length;
  8460. subMeshes = intersections.data;
  8461. }
  8462. else {
  8463. subMeshes = this.subMeshes;
  8464. len = subMeshes.length;
  8465. }
  8466. for (var index = 0; index < len; index++) {
  8467. var subMesh = subMeshes[index];
  8468. // Bounding test
  8469. if (len > 1 && !subMesh._checkCollision(collider))
  8470. continue;
  8471. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8472. }
  8473. };
  8474. AbstractMesh.prototype._checkCollision = function (collider) {
  8475. // Bounding box test
  8476. if (!this._boundingInfo._checkCollision(collider))
  8477. return;
  8478. // Transformation matrix
  8479. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8480. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8481. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8482. };
  8483. // Picking
  8484. AbstractMesh.prototype._generatePointsArray = function () {
  8485. return false;
  8486. };
  8487. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8488. var pickingInfo = new BABYLON.PickingInfo();
  8489. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8490. return pickingInfo;
  8491. }
  8492. if (!this._generatePointsArray()) {
  8493. return pickingInfo;
  8494. }
  8495. var intersectInfo = null;
  8496. // Octrees
  8497. var subMeshes;
  8498. var len;
  8499. if (this._submeshesOctree && this.useOctreeForPicking) {
  8500. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8501. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8502. len = intersections.length;
  8503. subMeshes = intersections.data;
  8504. }
  8505. else {
  8506. subMeshes = this.subMeshes;
  8507. len = subMeshes.length;
  8508. }
  8509. for (var index = 0; index < len; index++) {
  8510. var subMesh = subMeshes[index];
  8511. // Bounding test
  8512. if (len > 1 && !subMesh.canIntersects(ray))
  8513. continue;
  8514. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8515. if (currentIntersectInfo) {
  8516. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8517. intersectInfo = currentIntersectInfo;
  8518. intersectInfo.subMeshId = index;
  8519. if (fastCheck) {
  8520. break;
  8521. }
  8522. }
  8523. }
  8524. }
  8525. if (intersectInfo) {
  8526. // Get picked point
  8527. var world = this.getWorldMatrix();
  8528. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8529. var direction = ray.direction.clone();
  8530. direction = direction.scale(intersectInfo.distance);
  8531. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8532. var pickedPoint = worldOrigin.add(worldDirection);
  8533. // Return result
  8534. pickingInfo.hit = true;
  8535. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8536. pickingInfo.pickedPoint = pickedPoint;
  8537. pickingInfo.pickedMesh = this;
  8538. pickingInfo.bu = intersectInfo.bu;
  8539. pickingInfo.bv = intersectInfo.bv;
  8540. pickingInfo.faceId = intersectInfo.faceId;
  8541. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8542. return pickingInfo;
  8543. }
  8544. return pickingInfo;
  8545. };
  8546. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8547. return null;
  8548. };
  8549. AbstractMesh.prototype.releaseSubMeshes = function () {
  8550. if (this.subMeshes) {
  8551. while (this.subMeshes.length) {
  8552. this.subMeshes[0].dispose();
  8553. }
  8554. }
  8555. else {
  8556. this.subMeshes = new Array();
  8557. }
  8558. };
  8559. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8560. var index;
  8561. // Physics
  8562. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8563. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8564. }
  8565. // Intersections in progress
  8566. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8567. var other = this._intersectionsInProgress[index];
  8568. var pos = other._intersectionsInProgress.indexOf(this);
  8569. other._intersectionsInProgress.splice(pos, 1);
  8570. }
  8571. this._intersectionsInProgress = [];
  8572. // Edges
  8573. if (this._edgesRenderer) {
  8574. this._edgesRenderer.dispose();
  8575. this._edgesRenderer = null;
  8576. }
  8577. // SubMeshes
  8578. this.releaseSubMeshes();
  8579. // Remove from scene
  8580. this.getScene().removeMesh(this);
  8581. if (!doNotRecurse) {
  8582. // Particles
  8583. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8584. if (this.getScene().particleSystems[index].emitter === this) {
  8585. this.getScene().particleSystems[index].dispose();
  8586. index--;
  8587. }
  8588. }
  8589. // Children
  8590. var objects = this.getScene().meshes.slice(0);
  8591. for (index = 0; index < objects.length; index++) {
  8592. if (objects[index].parent === this) {
  8593. objects[index].dispose();
  8594. }
  8595. }
  8596. }
  8597. else {
  8598. for (index = 0; index < this.getScene().meshes.length; index++) {
  8599. var obj = this.getScene().meshes[index];
  8600. if (obj.parent === this) {
  8601. obj.parent = null;
  8602. obj.computeWorldMatrix(true);
  8603. }
  8604. }
  8605. }
  8606. this._onAfterWorldMatrixUpdate = [];
  8607. this._isDisposed = true;
  8608. // Callback
  8609. if (this.onDispose) {
  8610. this.onDispose();
  8611. }
  8612. };
  8613. // Statics
  8614. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8615. AbstractMesh._BILLBOARDMODE_X = 1;
  8616. AbstractMesh._BILLBOARDMODE_Y = 2;
  8617. AbstractMesh._BILLBOARDMODE_Z = 4;
  8618. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8619. return AbstractMesh;
  8620. })(BABYLON.Node);
  8621. BABYLON.AbstractMesh = AbstractMesh;
  8622. })(BABYLON || (BABYLON = {}));
  8623. var BABYLON;
  8624. (function (BABYLON) {
  8625. var Light = (function (_super) {
  8626. __extends(Light, _super);
  8627. function Light(name, scene) {
  8628. _super.call(this, name, scene);
  8629. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8630. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8631. this.intensity = 1.0;
  8632. this.range = Number.MAX_VALUE;
  8633. this.includeOnlyWithLayerMask = 0;
  8634. this.includedOnlyMeshes = new Array();
  8635. this.excludedMeshes = new Array();
  8636. this.excludeWithLayerMask = 0;
  8637. this._excludedMeshesIds = new Array();
  8638. this._includedOnlyMeshesIds = new Array();
  8639. scene.addLight(this);
  8640. }
  8641. Light.prototype.getShadowGenerator = function () {
  8642. return this._shadowGenerator;
  8643. };
  8644. Light.prototype.getAbsolutePosition = function () {
  8645. return BABYLON.Vector3.Zero();
  8646. };
  8647. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8648. };
  8649. Light.prototype._getWorldMatrix = function () {
  8650. return BABYLON.Matrix.Identity();
  8651. };
  8652. Light.prototype.canAffectMesh = function (mesh) {
  8653. if (!mesh) {
  8654. return true;
  8655. }
  8656. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8657. return false;
  8658. }
  8659. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8660. return false;
  8661. }
  8662. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8663. return false;
  8664. }
  8665. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8666. return false;
  8667. }
  8668. return true;
  8669. };
  8670. Light.prototype.getWorldMatrix = function () {
  8671. this._currentRenderId = this.getScene().getRenderId();
  8672. var worldMatrix = this._getWorldMatrix();
  8673. if (this.parent && this.parent.getWorldMatrix) {
  8674. if (!this._parentedWorldMatrix) {
  8675. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8676. }
  8677. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8678. this._markSyncedWithParent();
  8679. return this._parentedWorldMatrix;
  8680. }
  8681. return worldMatrix;
  8682. };
  8683. Light.prototype.dispose = function () {
  8684. if (this._shadowGenerator) {
  8685. this._shadowGenerator.dispose();
  8686. this._shadowGenerator = null;
  8687. }
  8688. // Remove from scene
  8689. this.getScene().removeLight(this);
  8690. };
  8691. return Light;
  8692. })(BABYLON.Node);
  8693. BABYLON.Light = Light;
  8694. })(BABYLON || (BABYLON = {}));
  8695. var BABYLON;
  8696. (function (BABYLON) {
  8697. var PointLight = (function (_super) {
  8698. __extends(PointLight, _super);
  8699. function PointLight(name, position, scene) {
  8700. _super.call(this, name, scene);
  8701. this.position = position;
  8702. }
  8703. PointLight.prototype.getAbsolutePosition = function () {
  8704. return this._transformedPosition ? this._transformedPosition : this.position;
  8705. };
  8706. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8707. if (this.parent && this.parent.getWorldMatrix) {
  8708. if (!this._transformedPosition) {
  8709. this._transformedPosition = BABYLON.Vector3.Zero();
  8710. }
  8711. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8712. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8713. return;
  8714. }
  8715. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8716. };
  8717. PointLight.prototype.getShadowGenerator = function () {
  8718. return null;
  8719. };
  8720. PointLight.prototype._getWorldMatrix = function () {
  8721. if (!this._worldMatrix) {
  8722. this._worldMatrix = BABYLON.Matrix.Identity();
  8723. }
  8724. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8725. return this._worldMatrix;
  8726. };
  8727. return PointLight;
  8728. })(BABYLON.Light);
  8729. BABYLON.PointLight = PointLight;
  8730. })(BABYLON || (BABYLON = {}));
  8731. var BABYLON;
  8732. (function (BABYLON) {
  8733. var SpotLight = (function (_super) {
  8734. __extends(SpotLight, _super);
  8735. function SpotLight(name, position, direction, angle, exponent, scene) {
  8736. _super.call(this, name, scene);
  8737. this.position = position;
  8738. this.direction = direction;
  8739. this.angle = angle;
  8740. this.exponent = exponent;
  8741. }
  8742. SpotLight.prototype.getAbsolutePosition = function () {
  8743. return this.transformedPosition ? this.transformedPosition : this.position;
  8744. };
  8745. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8746. var activeCamera = this.getScene().activeCamera;
  8747. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8748. };
  8749. SpotLight.prototype.supportsVSM = function () {
  8750. return true;
  8751. };
  8752. SpotLight.prototype.needRefreshPerFrame = function () {
  8753. return false;
  8754. };
  8755. SpotLight.prototype.setDirectionToTarget = function (target) {
  8756. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8757. return this.direction;
  8758. };
  8759. SpotLight.prototype.computeTransformedPosition = function () {
  8760. if (this.parent && this.parent.getWorldMatrix) {
  8761. if (!this.transformedPosition) {
  8762. this.transformedPosition = BABYLON.Vector3.Zero();
  8763. }
  8764. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8765. return true;
  8766. }
  8767. return false;
  8768. };
  8769. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8770. var normalizeDirection;
  8771. if (this.parent && this.parent.getWorldMatrix) {
  8772. if (!this._transformedDirection) {
  8773. this._transformedDirection = BABYLON.Vector3.Zero();
  8774. }
  8775. this.computeTransformedPosition();
  8776. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8777. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8778. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8779. }
  8780. else {
  8781. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8782. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8783. }
  8784. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8785. };
  8786. SpotLight.prototype._getWorldMatrix = function () {
  8787. if (!this._worldMatrix) {
  8788. this._worldMatrix = BABYLON.Matrix.Identity();
  8789. }
  8790. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8791. return this._worldMatrix;
  8792. };
  8793. return SpotLight;
  8794. })(BABYLON.Light);
  8795. BABYLON.SpotLight = SpotLight;
  8796. })(BABYLON || (BABYLON = {}));
  8797. var BABYLON;
  8798. (function (BABYLON) {
  8799. var HemisphericLight = (function (_super) {
  8800. __extends(HemisphericLight, _super);
  8801. function HemisphericLight(name, direction, scene) {
  8802. _super.call(this, name, scene);
  8803. this.direction = direction;
  8804. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8805. }
  8806. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8807. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8808. return this.direction;
  8809. };
  8810. HemisphericLight.prototype.getShadowGenerator = function () {
  8811. return null;
  8812. };
  8813. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8814. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8815. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8816. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8817. };
  8818. HemisphericLight.prototype._getWorldMatrix = function () {
  8819. if (!this._worldMatrix) {
  8820. this._worldMatrix = BABYLON.Matrix.Identity();
  8821. }
  8822. return this._worldMatrix;
  8823. };
  8824. return HemisphericLight;
  8825. })(BABYLON.Light);
  8826. BABYLON.HemisphericLight = HemisphericLight;
  8827. })(BABYLON || (BABYLON = {}));
  8828. var BABYLON;
  8829. (function (BABYLON) {
  8830. var DirectionalLight = (function (_super) {
  8831. __extends(DirectionalLight, _super);
  8832. function DirectionalLight(name, direction, scene) {
  8833. _super.call(this, name, scene);
  8834. this.direction = direction;
  8835. this.shadowOrthoScale = 0.5;
  8836. this.position = direction.scale(-1);
  8837. }
  8838. DirectionalLight.prototype.getAbsolutePosition = function () {
  8839. return this.transformedPosition ? this.transformedPosition : this.position;
  8840. };
  8841. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8842. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8843. return this.direction;
  8844. };
  8845. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8846. var orthoLeft = Number.MAX_VALUE;
  8847. var orthoRight = Number.MIN_VALUE;
  8848. var orthoTop = Number.MIN_VALUE;
  8849. var orthoBottom = Number.MAX_VALUE;
  8850. var tempVector3 = BABYLON.Vector3.Zero();
  8851. var activeCamera = this.getScene().activeCamera;
  8852. // Check extends
  8853. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8854. var mesh = renderList[meshIndex];
  8855. if (!mesh) {
  8856. continue;
  8857. }
  8858. var boundingInfo = mesh.getBoundingInfo();
  8859. if (!boundingInfo) {
  8860. continue;
  8861. }
  8862. var boundingBox = boundingInfo.boundingBox;
  8863. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8864. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8865. if (tempVector3.x < orthoLeft)
  8866. orthoLeft = tempVector3.x;
  8867. if (tempVector3.y < orthoBottom)
  8868. orthoBottom = tempVector3.y;
  8869. if (tempVector3.x > orthoRight)
  8870. orthoRight = tempVector3.x;
  8871. if (tempVector3.y > orthoTop)
  8872. orthoTop = tempVector3.y;
  8873. }
  8874. }
  8875. var xOffset = orthoRight - orthoLeft;
  8876. var yOffset = orthoTop - orthoBottom;
  8877. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8878. };
  8879. DirectionalLight.prototype.supportsVSM = function () {
  8880. return true;
  8881. };
  8882. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8883. return true;
  8884. };
  8885. DirectionalLight.prototype.computeTransformedPosition = function () {
  8886. if (this.parent && this.parent.getWorldMatrix) {
  8887. if (!this.transformedPosition) {
  8888. this.transformedPosition = BABYLON.Vector3.Zero();
  8889. }
  8890. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8891. return true;
  8892. }
  8893. return false;
  8894. };
  8895. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8896. if (this.parent && this.parent.getWorldMatrix) {
  8897. if (!this._transformedDirection) {
  8898. this._transformedDirection = BABYLON.Vector3.Zero();
  8899. }
  8900. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8901. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8902. return;
  8903. }
  8904. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8905. };
  8906. DirectionalLight.prototype._getWorldMatrix = function () {
  8907. if (!this._worldMatrix) {
  8908. this._worldMatrix = BABYLON.Matrix.Identity();
  8909. }
  8910. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8911. return this._worldMatrix;
  8912. };
  8913. return DirectionalLight;
  8914. })(BABYLON.Light);
  8915. BABYLON.DirectionalLight = DirectionalLight;
  8916. })(BABYLON || (BABYLON = {}));
  8917. var BABYLON;
  8918. (function (BABYLON) {
  8919. var ShadowGenerator = (function () {
  8920. function ShadowGenerator(mapSize, light) {
  8921. var _this = this;
  8922. // Members
  8923. this._filter = ShadowGenerator.FILTER_NONE;
  8924. this.blurScale = 2;
  8925. this._blurBoxOffset = 0;
  8926. this._bias = 0.00005;
  8927. this._lightDirection = BABYLON.Vector3.Zero();
  8928. this._darkness = 0;
  8929. this._transparencyShadow = false;
  8930. this._viewMatrix = BABYLON.Matrix.Zero();
  8931. this._projectionMatrix = BABYLON.Matrix.Zero();
  8932. this._transformMatrix = BABYLON.Matrix.Zero();
  8933. this._worldViewProjection = BABYLON.Matrix.Zero();
  8934. this._light = light;
  8935. this._scene = light.getScene();
  8936. this._mapSize = mapSize;
  8937. light._shadowGenerator = this;
  8938. // Render target
  8939. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8940. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8941. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8942. this._shadowMap.anisotropicFilteringLevel = 1;
  8943. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8944. this._shadowMap.renderParticles = false;
  8945. this._shadowMap.onAfterUnbind = function () {
  8946. if (!_this.useBlurVarianceShadowMap) {
  8947. return;
  8948. }
  8949. if (!_this._shadowMap2) {
  8950. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8951. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8952. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8953. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8954. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8955. _this._downSamplePostprocess.onApply = function (effect) {
  8956. effect.setTexture("textureSampler", _this._shadowMap);
  8957. };
  8958. _this.blurBoxOffset = 1;
  8959. }
  8960. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8961. };
  8962. // Custom render function
  8963. var renderSubMesh = function (subMesh) {
  8964. var mesh = subMesh.getRenderingMesh();
  8965. var scene = _this._scene;
  8966. var engine = scene.getEngine();
  8967. // Culling
  8968. engine.setState(subMesh.getMaterial().backFaceCulling);
  8969. // Managing instances
  8970. var batch = mesh._getInstancesRenderList(subMesh._id);
  8971. if (batch.mustReturn) {
  8972. return;
  8973. }
  8974. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8975. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8976. engine.enableEffect(_this._effect);
  8977. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8978. var material = subMesh.getMaterial();
  8979. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8980. // Alpha test
  8981. if (material && material.needAlphaTesting()) {
  8982. var alphaTexture = material.getAlphaTestTexture();
  8983. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8984. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8985. }
  8986. // Bones
  8987. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8989. }
  8990. // Draw
  8991. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8992. }
  8993. else {
  8994. // Need to reset refresh rate of the shadowMap
  8995. _this._shadowMap.resetRefreshCounter();
  8996. }
  8997. };
  8998. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8999. var index;
  9000. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9001. renderSubMesh(opaqueSubMeshes.data[index]);
  9002. }
  9003. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9004. renderSubMesh(alphaTestSubMeshes.data[index]);
  9005. }
  9006. if (_this._transparencyShadow) {
  9007. for (index = 0; index < transparentSubMeshes.length; index++) {
  9008. renderSubMesh(transparentSubMeshes.data[index]);
  9009. }
  9010. }
  9011. };
  9012. this._shadowMap.onClear = function (engine) {
  9013. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9014. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9015. }
  9016. else {
  9017. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9018. }
  9019. };
  9020. }
  9021. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9022. // Static
  9023. get: function () {
  9024. return ShadowGenerator._FILTER_NONE;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9030. get: function () {
  9031. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9037. get: function () {
  9038. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9044. get: function () {
  9045. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9046. },
  9047. enumerable: true,
  9048. configurable: true
  9049. });
  9050. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9051. get: function () {
  9052. return this._bias;
  9053. },
  9054. set: function (bias) {
  9055. this._bias = bias;
  9056. },
  9057. enumerable: true,
  9058. configurable: true
  9059. });
  9060. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9061. get: function () {
  9062. return this._blurBoxOffset;
  9063. },
  9064. set: function (value) {
  9065. var _this = this;
  9066. if (this._blurBoxOffset === value) {
  9067. return;
  9068. }
  9069. this._blurBoxOffset = value;
  9070. if (this._boxBlurPostprocess) {
  9071. this._boxBlurPostprocess.dispose();
  9072. }
  9073. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9074. this._boxBlurPostprocess.onApply = function (effect) {
  9075. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9076. };
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9082. get: function () {
  9083. return this._filter;
  9084. },
  9085. set: function (value) {
  9086. if (this._filter === value) {
  9087. return;
  9088. }
  9089. this._filter = value;
  9090. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9091. this._shadowMap.anisotropicFilteringLevel = 16;
  9092. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9093. }
  9094. else {
  9095. this._shadowMap.anisotropicFilteringLevel = 1;
  9096. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9097. }
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9103. get: function () {
  9104. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9105. },
  9106. set: function (value) {
  9107. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9108. },
  9109. enumerable: true,
  9110. configurable: true
  9111. });
  9112. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9113. get: function () {
  9114. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9115. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9116. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9117. },
  9118. set: function (value) {
  9119. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9125. get: function () {
  9126. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9127. },
  9128. set: function (value) {
  9129. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9130. },
  9131. enumerable: true,
  9132. configurable: true
  9133. });
  9134. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9135. var defines = [];
  9136. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9137. defines.push("#define VSM");
  9138. }
  9139. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9140. var mesh = subMesh.getMesh();
  9141. var material = subMesh.getMaterial();
  9142. // Alpha test
  9143. if (material && material.needAlphaTesting()) {
  9144. defines.push("#define ALPHATEST");
  9145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9146. attribs.push(BABYLON.VertexBuffer.UVKind);
  9147. defines.push("#define UV1");
  9148. }
  9149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9150. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9151. defines.push("#define UV2");
  9152. }
  9153. }
  9154. // Bones
  9155. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9156. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9157. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9158. defines.push("#define BONES");
  9159. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9160. }
  9161. // Instances
  9162. if (useInstances) {
  9163. defines.push("#define INSTANCES");
  9164. attribs.push("world0");
  9165. attribs.push("world1");
  9166. attribs.push("world2");
  9167. attribs.push("world3");
  9168. }
  9169. // Get correct effect
  9170. var join = defines.join("\n");
  9171. if (this._cachedDefines !== join) {
  9172. this._cachedDefines = join;
  9173. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9174. }
  9175. return this._effect.isReady();
  9176. };
  9177. ShadowGenerator.prototype.getShadowMap = function () {
  9178. return this._shadowMap;
  9179. };
  9180. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9181. if (this._shadowMap2) {
  9182. return this._shadowMap2;
  9183. }
  9184. return this._shadowMap;
  9185. };
  9186. ShadowGenerator.prototype.getLight = function () {
  9187. return this._light;
  9188. };
  9189. // Methods
  9190. ShadowGenerator.prototype.getTransformMatrix = function () {
  9191. var scene = this._scene;
  9192. if (this._currentRenderID === scene.getRenderId()) {
  9193. return this._transformMatrix;
  9194. }
  9195. this._currentRenderID = scene.getRenderId();
  9196. var lightPosition = this._light.position;
  9197. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9198. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9199. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9200. }
  9201. if (this._light.computeTransformedPosition()) {
  9202. lightPosition = this._light.transformedPosition;
  9203. }
  9204. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9205. this._cachedPosition = lightPosition.clone();
  9206. this._cachedDirection = this._lightDirection.clone();
  9207. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9208. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9209. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9210. }
  9211. return this._transformMatrix;
  9212. };
  9213. ShadowGenerator.prototype.getDarkness = function () {
  9214. return this._darkness;
  9215. };
  9216. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9217. if (darkness >= 1.0)
  9218. this._darkness = 1.0;
  9219. else if (darkness <= 0.0)
  9220. this._darkness = 0.0;
  9221. else
  9222. this._darkness = darkness;
  9223. };
  9224. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9225. this._transparencyShadow = hasShadow;
  9226. };
  9227. ShadowGenerator.prototype._packHalf = function (depth) {
  9228. var scale = depth * 255.0;
  9229. var fract = scale - Math.floor(scale);
  9230. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9231. };
  9232. ShadowGenerator.prototype.dispose = function () {
  9233. this._shadowMap.dispose();
  9234. if (this._shadowMap2) {
  9235. this._shadowMap2.dispose();
  9236. }
  9237. if (this._downSamplePostprocess) {
  9238. this._downSamplePostprocess.dispose();
  9239. }
  9240. if (this._boxBlurPostprocess) {
  9241. this._boxBlurPostprocess.dispose();
  9242. }
  9243. };
  9244. ShadowGenerator._FILTER_NONE = 0;
  9245. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9246. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9247. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9248. return ShadowGenerator;
  9249. })();
  9250. BABYLON.ShadowGenerator = ShadowGenerator;
  9251. })(BABYLON || (BABYLON = {}));
  9252. var BABYLON;
  9253. (function (BABYLON) {
  9254. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9255. if (boxMin.x > sphereCenter.x + sphereRadius)
  9256. return false;
  9257. if (sphereCenter.x - sphereRadius > boxMax.x)
  9258. return false;
  9259. if (boxMin.y > sphereCenter.y + sphereRadius)
  9260. return false;
  9261. if (sphereCenter.y - sphereRadius > boxMax.y)
  9262. return false;
  9263. if (boxMin.z > sphereCenter.z + sphereRadius)
  9264. return false;
  9265. if (sphereCenter.z - sphereRadius > boxMax.z)
  9266. return false;
  9267. return true;
  9268. };
  9269. var getLowestRoot = function (a, b, c, maxR) {
  9270. var determinant = b * b - 4.0 * a * c;
  9271. var result = { root: 0, found: false };
  9272. if (determinant < 0)
  9273. return result;
  9274. var sqrtD = Math.sqrt(determinant);
  9275. var r1 = (-b - sqrtD) / (2.0 * a);
  9276. var r2 = (-b + sqrtD) / (2.0 * a);
  9277. if (r1 > r2) {
  9278. var temp = r2;
  9279. r2 = r1;
  9280. r1 = temp;
  9281. }
  9282. if (r1 > 0 && r1 < maxR) {
  9283. result.root = r1;
  9284. result.found = true;
  9285. return result;
  9286. }
  9287. if (r2 > 0 && r2 < maxR) {
  9288. result.root = r2;
  9289. result.found = true;
  9290. return result;
  9291. }
  9292. return result;
  9293. };
  9294. var Collider = (function () {
  9295. function Collider() {
  9296. this.radius = new BABYLON.Vector3(1, 1, 1);
  9297. this.retry = 0;
  9298. this.basePointWorld = BABYLON.Vector3.Zero();
  9299. this.velocityWorld = BABYLON.Vector3.Zero();
  9300. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9301. this._collisionPoint = BABYLON.Vector3.Zero();
  9302. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9303. this._tempVector = BABYLON.Vector3.Zero();
  9304. this._tempVector2 = BABYLON.Vector3.Zero();
  9305. this._tempVector3 = BABYLON.Vector3.Zero();
  9306. this._tempVector4 = BABYLON.Vector3.Zero();
  9307. this._edge = BABYLON.Vector3.Zero();
  9308. this._baseToVertex = BABYLON.Vector3.Zero();
  9309. this._destinationPoint = BABYLON.Vector3.Zero();
  9310. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9311. this._displacementVector = BABYLON.Vector3.Zero();
  9312. }
  9313. // Methods
  9314. Collider.prototype._initialize = function (source, dir, e) {
  9315. this.velocity = dir;
  9316. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9317. this.basePoint = source;
  9318. source.multiplyToRef(this.radius, this.basePointWorld);
  9319. dir.multiplyToRef(this.radius, this.velocityWorld);
  9320. this.velocityWorldLength = this.velocityWorld.length();
  9321. this.epsilon = e;
  9322. this.collisionFound = false;
  9323. };
  9324. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9325. pa.subtractToRef(point, this._tempVector);
  9326. pb.subtractToRef(point, this._tempVector2);
  9327. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9328. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9329. if (d < 0)
  9330. return false;
  9331. pc.subtractToRef(point, this._tempVector3);
  9332. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9333. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9334. if (d < 0)
  9335. return false;
  9336. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9337. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9338. return d >= 0;
  9339. };
  9340. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9341. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9342. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9343. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9344. return false;
  9345. }
  9346. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9347. return false;
  9348. return true;
  9349. };
  9350. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9351. var t0;
  9352. var embeddedInPlane = false;
  9353. //defensive programming, actually not needed.
  9354. if (!trianglePlaneArray) {
  9355. trianglePlaneArray = [];
  9356. }
  9357. if (!trianglePlaneArray[faceIndex]) {
  9358. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9359. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9360. }
  9361. var trianglePlane = trianglePlaneArray[faceIndex];
  9362. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9363. return;
  9364. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9365. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9366. if (normalDotVelocity == 0) {
  9367. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9368. return;
  9369. embeddedInPlane = true;
  9370. t0 = 0;
  9371. }
  9372. else {
  9373. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9374. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9375. if (t0 > t1) {
  9376. var temp = t1;
  9377. t1 = t0;
  9378. t0 = temp;
  9379. }
  9380. if (t0 > 1.0 || t1 < 0.0)
  9381. return;
  9382. if (t0 < 0)
  9383. t0 = 0;
  9384. if (t0 > 1.0)
  9385. t0 = 1.0;
  9386. }
  9387. this._collisionPoint.copyFromFloats(0, 0, 0);
  9388. var found = false;
  9389. var t = 1.0;
  9390. if (!embeddedInPlane) {
  9391. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9392. this.velocity.scaleToRef(t0, this._tempVector);
  9393. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9394. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9395. found = true;
  9396. t = t0;
  9397. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9398. }
  9399. }
  9400. if (!found) {
  9401. var velocitySquaredLength = this.velocity.lengthSquared();
  9402. var a = velocitySquaredLength;
  9403. this.basePoint.subtractToRef(p1, this._tempVector);
  9404. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9405. var c = this._tempVector.lengthSquared() - 1.0;
  9406. var lowestRoot = getLowestRoot(a, b, c, t);
  9407. if (lowestRoot.found) {
  9408. t = lowestRoot.root;
  9409. found = true;
  9410. this._collisionPoint.copyFrom(p1);
  9411. }
  9412. this.basePoint.subtractToRef(p2, this._tempVector);
  9413. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9414. c = this._tempVector.lengthSquared() - 1.0;
  9415. lowestRoot = getLowestRoot(a, b, c, t);
  9416. if (lowestRoot.found) {
  9417. t = lowestRoot.root;
  9418. found = true;
  9419. this._collisionPoint.copyFrom(p2);
  9420. }
  9421. this.basePoint.subtractToRef(p3, this._tempVector);
  9422. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9423. c = this._tempVector.lengthSquared() - 1.0;
  9424. lowestRoot = getLowestRoot(a, b, c, t);
  9425. if (lowestRoot.found) {
  9426. t = lowestRoot.root;
  9427. found = true;
  9428. this._collisionPoint.copyFrom(p3);
  9429. }
  9430. p2.subtractToRef(p1, this._edge);
  9431. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9432. var edgeSquaredLength = this._edge.lengthSquared();
  9433. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9434. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9435. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9436. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9437. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9438. lowestRoot = getLowestRoot(a, b, c, t);
  9439. if (lowestRoot.found) {
  9440. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9441. if (f >= 0.0 && f <= 1.0) {
  9442. t = lowestRoot.root;
  9443. found = true;
  9444. this._edge.scaleInPlace(f);
  9445. p1.addToRef(this._edge, this._collisionPoint);
  9446. }
  9447. }
  9448. p3.subtractToRef(p2, this._edge);
  9449. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9450. edgeSquaredLength = this._edge.lengthSquared();
  9451. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9452. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9453. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9454. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9455. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9456. lowestRoot = getLowestRoot(a, b, c, t);
  9457. if (lowestRoot.found) {
  9458. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9459. if (f >= 0.0 && f <= 1.0) {
  9460. t = lowestRoot.root;
  9461. found = true;
  9462. this._edge.scaleInPlace(f);
  9463. p2.addToRef(this._edge, this._collisionPoint);
  9464. }
  9465. }
  9466. p1.subtractToRef(p3, this._edge);
  9467. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9468. edgeSquaredLength = this._edge.lengthSquared();
  9469. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9470. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9471. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9472. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9473. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9474. lowestRoot = getLowestRoot(a, b, c, t);
  9475. if (lowestRoot.found) {
  9476. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9477. if (f >= 0.0 && f <= 1.0) {
  9478. t = lowestRoot.root;
  9479. found = true;
  9480. this._edge.scaleInPlace(f);
  9481. p3.addToRef(this._edge, this._collisionPoint);
  9482. }
  9483. }
  9484. }
  9485. if (found) {
  9486. var distToCollision = t * this.velocity.length();
  9487. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9488. if (!this.intersectionPoint) {
  9489. this.intersectionPoint = this._collisionPoint.clone();
  9490. }
  9491. else {
  9492. this.intersectionPoint.copyFrom(this._collisionPoint);
  9493. }
  9494. this.nearestDistance = distToCollision;
  9495. this.collisionFound = true;
  9496. }
  9497. }
  9498. };
  9499. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9500. for (var i = indexStart; i < indexEnd; i += 3) {
  9501. var p1 = pts[indices[i] - decal];
  9502. var p2 = pts[indices[i + 1] - decal];
  9503. var p3 = pts[indices[i + 2] - decal];
  9504. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9505. }
  9506. };
  9507. Collider.prototype._getResponse = function (pos, vel) {
  9508. pos.addToRef(vel, this._destinationPoint);
  9509. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9510. this.basePoint.addToRef(vel, pos);
  9511. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9512. this._slidePlaneNormal.normalize();
  9513. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9514. pos.addInPlace(this._displacementVector);
  9515. this.intersectionPoint.addInPlace(this._displacementVector);
  9516. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9517. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9518. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9519. };
  9520. return Collider;
  9521. })();
  9522. BABYLON.Collider = Collider;
  9523. })(BABYLON || (BABYLON = {}));
  9524. var BABYLON;
  9525. (function (BABYLON) {
  9526. //WebWorker code will be inserted to this variable.
  9527. BABYLON.CollisionWorker = "";
  9528. (function (WorkerTaskType) {
  9529. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9530. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9531. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9532. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9533. var WorkerTaskType = BABYLON.WorkerTaskType;
  9534. (function (WorkerReplyType) {
  9535. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9536. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9537. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9538. var WorkerReplyType = BABYLON.WorkerReplyType;
  9539. var CollisionCoordinatorWorker = (function () {
  9540. function CollisionCoordinatorWorker() {
  9541. var _this = this;
  9542. this._scaledPosition = BABYLON.Vector3.Zero();
  9543. this._scaledVelocity = BABYLON.Vector3.Zero();
  9544. this.onMeshUpdated = function (mesh) {
  9545. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9546. };
  9547. this.onGeometryUpdated = function (geometry) {
  9548. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9549. };
  9550. this._afterRender = function () {
  9551. if (!_this._init)
  9552. return;
  9553. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9554. return;
  9555. }
  9556. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9557. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9558. if (_this._runningUpdated > 4) {
  9559. return;
  9560. }
  9561. ++_this._runningUpdated;
  9562. var payload = {
  9563. updatedMeshes: _this._addUpdateMeshesList,
  9564. updatedGeometries: _this._addUpdateGeometriesList,
  9565. removedGeometries: _this._toRemoveGeometryArray,
  9566. removedMeshes: _this._toRemoveMeshesArray
  9567. };
  9568. var message = {
  9569. payload: payload,
  9570. taskType: WorkerTaskType.UPDATE
  9571. };
  9572. var serializable = [];
  9573. for (var id in payload.updatedGeometries) {
  9574. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9575. //prepare transferables
  9576. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9577. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9578. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9579. }
  9580. }
  9581. _this._worker.postMessage(message, serializable);
  9582. _this._addUpdateMeshesList = {};
  9583. _this._addUpdateGeometriesList = {};
  9584. _this._toRemoveGeometryArray = [];
  9585. _this._toRemoveMeshesArray = [];
  9586. };
  9587. this._onMessageFromWorker = function (e) {
  9588. var returnData = e.data;
  9589. if (returnData.error != WorkerReplyType.SUCCESS) {
  9590. //TODO what errors can be returned from the worker?
  9591. BABYLON.Tools.Warn("error returned from worker!");
  9592. return;
  9593. }
  9594. switch (returnData.taskType) {
  9595. case WorkerTaskType.INIT:
  9596. _this._init = true;
  9597. //Update the worked with ALL of the scene's current state
  9598. _this._scene.meshes.forEach(function (mesh) {
  9599. _this.onMeshAdded(mesh);
  9600. });
  9601. _this._scene.getGeometries().forEach(function (geometry) {
  9602. _this.onGeometryAdded(geometry);
  9603. });
  9604. break;
  9605. case WorkerTaskType.UPDATE:
  9606. _this._runningUpdated--;
  9607. break;
  9608. case WorkerTaskType.COLLIDE:
  9609. _this._runningCollisionTask = false;
  9610. var returnPayload = returnData.payload;
  9611. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9612. return;
  9613. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9614. //cleanup
  9615. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9616. break;
  9617. }
  9618. };
  9619. this._collisionsCallbackArray = [];
  9620. this._init = false;
  9621. this._runningUpdated = 0;
  9622. this._runningCollisionTask = false;
  9623. this._addUpdateMeshesList = {};
  9624. this._addUpdateGeometriesList = {};
  9625. this._toRemoveGeometryArray = [];
  9626. this._toRemoveMeshesArray = [];
  9627. }
  9628. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9629. if (!this._init)
  9630. return;
  9631. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9632. return;
  9633. position.divideToRef(collider.radius, this._scaledPosition);
  9634. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9635. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9636. var payload = {
  9637. collider: {
  9638. position: this._scaledPosition.asArray(),
  9639. velocity: this._scaledVelocity.asArray(),
  9640. radius: collider.radius.asArray()
  9641. },
  9642. collisionId: collisionIndex,
  9643. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9644. maximumRetry: maximumRetry
  9645. };
  9646. var message = {
  9647. payload: payload,
  9648. taskType: WorkerTaskType.COLLIDE
  9649. };
  9650. this._worker.postMessage(message);
  9651. };
  9652. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9653. this._scene = scene;
  9654. this._scene.registerAfterRender(this._afterRender);
  9655. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9656. this._worker = new Worker(workerUrl);
  9657. this._worker.onmessage = this._onMessageFromWorker;
  9658. var message = {
  9659. payload: {},
  9660. taskType: WorkerTaskType.INIT
  9661. };
  9662. this._worker.postMessage(message);
  9663. };
  9664. CollisionCoordinatorWorker.prototype.destroy = function () {
  9665. this._scene.unregisterAfterRender(this._afterRender);
  9666. this._worker.terminate();
  9667. };
  9668. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9669. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9670. this.onMeshUpdated(mesh);
  9671. };
  9672. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9673. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9674. };
  9675. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9676. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9677. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9678. this.onGeometryUpdated(geometry);
  9679. };
  9680. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9681. this._toRemoveGeometryArray.push(geometry.id);
  9682. };
  9683. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9684. var submeshes = [];
  9685. if (mesh.subMeshes) {
  9686. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9687. return {
  9688. position: idx,
  9689. verticesStart: sm.verticesStart,
  9690. verticesCount: sm.verticesCount,
  9691. indexStart: sm.indexStart,
  9692. indexCount: sm.indexCount,
  9693. hasMaterial: !!sm.getMaterial(),
  9694. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9695. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9696. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9697. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9698. };
  9699. });
  9700. }
  9701. var geometryId = null;
  9702. if (mesh instanceof BABYLON.Mesh) {
  9703. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9704. }
  9705. else if (mesh instanceof BABYLON.InstancedMesh) {
  9706. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9707. }
  9708. return {
  9709. uniqueId: mesh.uniqueId,
  9710. id: mesh.id,
  9711. name: mesh.name,
  9712. geometryId: geometryId,
  9713. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9714. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9715. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9716. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9717. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9718. subMeshes: submeshes,
  9719. checkCollisions: mesh.checkCollisions
  9720. };
  9721. };
  9722. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9723. return {
  9724. id: geometry.id,
  9725. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9726. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9727. indices: new Int32Array(geometry.getIndices() || []),
  9728. };
  9729. };
  9730. return CollisionCoordinatorWorker;
  9731. })();
  9732. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9733. var CollisionCoordinatorLegacy = (function () {
  9734. function CollisionCoordinatorLegacy() {
  9735. this._scaledPosition = BABYLON.Vector3.Zero();
  9736. this._scaledVelocity = BABYLON.Vector3.Zero();
  9737. this._finalPosition = BABYLON.Vector3.Zero();
  9738. }
  9739. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9740. position.divideToRef(collider.radius, this._scaledPosition);
  9741. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9742. collider.collidedMesh = null;
  9743. collider.retry = 0;
  9744. collider.initialVelocity = this._scaledVelocity;
  9745. collider.initialPosition = this._scaledPosition;
  9746. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9747. this._finalPosition.multiplyInPlace(collider.radius);
  9748. //run the callback
  9749. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9750. };
  9751. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9752. this._scene = scene;
  9753. };
  9754. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9755. //Legacy need no destruction method.
  9756. };
  9757. //No update in legacy mode
  9758. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9759. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9760. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9761. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9762. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9763. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9764. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9765. if (excludedMesh === void 0) { excludedMesh = null; }
  9766. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9767. if (collider.retry >= maximumRetry) {
  9768. finalPosition.copyFrom(position);
  9769. return;
  9770. }
  9771. collider._initialize(position, velocity, closeDistance);
  9772. // Check all meshes
  9773. for (var index = 0; index < this._scene.meshes.length; index++) {
  9774. var mesh = this._scene.meshes[index];
  9775. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9776. mesh._checkCollision(collider);
  9777. }
  9778. }
  9779. if (!collider.collisionFound) {
  9780. position.addToRef(velocity, finalPosition);
  9781. return;
  9782. }
  9783. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9784. collider._getResponse(position, velocity);
  9785. }
  9786. if (velocity.length() <= closeDistance) {
  9787. finalPosition.copyFrom(position);
  9788. return;
  9789. }
  9790. collider.retry++;
  9791. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9792. };
  9793. return CollisionCoordinatorLegacy;
  9794. })();
  9795. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9796. })(BABYLON || (BABYLON = {}));
  9797. var BABYLON;
  9798. (function (BABYLON) {
  9799. var VRCameraMetrics = (function () {
  9800. function VRCameraMetrics() {
  9801. this.compensateDistorsion = true;
  9802. }
  9803. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9804. get: function () {
  9805. return this.hResolution / (2 * this.vResolution);
  9806. },
  9807. enumerable: true,
  9808. configurable: true
  9809. });
  9810. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9811. get: function () {
  9812. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9818. get: function () {
  9819. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9820. var h = (4 * meters) / this.hScreenSize;
  9821. return BABYLON.Matrix.Translation(h, 0, 0);
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9827. get: function () {
  9828. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9829. var h = (4 * meters) / this.hScreenSize;
  9830. return BABYLON.Matrix.Translation(-h, 0, 0);
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9836. get: function () {
  9837. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9843. get: function () {
  9844. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. VRCameraMetrics.GetDefault = function () {
  9850. var result = new VRCameraMetrics();
  9851. result.hResolution = 1280;
  9852. result.vResolution = 800;
  9853. result.hScreenSize = 0.149759993;
  9854. result.vScreenSize = 0.0935999975;
  9855. result.vScreenCenter = 0.0467999987,
  9856. result.eyeToScreenDistance = 0.0410000011;
  9857. result.lensSeparationDistance = 0.0635000020;
  9858. result.interpupillaryDistance = 0.0640000030;
  9859. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9860. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9861. result.postProcessScaleFactor = 1.714605507808412;
  9862. result.lensCenterOffset = 0.151976421;
  9863. return result;
  9864. };
  9865. return VRCameraMetrics;
  9866. })();
  9867. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9868. var Camera = (function (_super) {
  9869. __extends(Camera, _super);
  9870. function Camera(name, position, scene) {
  9871. _super.call(this, name, scene);
  9872. this.position = position;
  9873. // Members
  9874. this.upVector = BABYLON.Vector3.Up();
  9875. this.orthoLeft = null;
  9876. this.orthoRight = null;
  9877. this.orthoBottom = null;
  9878. this.orthoTop = null;
  9879. this.fov = 0.8;
  9880. this.minZ = 1.0;
  9881. this.maxZ = 10000.0;
  9882. this.inertia = 0.9;
  9883. this.mode = Camera.PERSPECTIVE_CAMERA;
  9884. this.isIntermediate = false;
  9885. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9886. this.layerMask = 0x0FFFFFFF;
  9887. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9888. // Camera rig members
  9889. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9890. this._rigCameras = new Array();
  9891. // Cache
  9892. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9893. this._projectionMatrix = new BABYLON.Matrix();
  9894. this._postProcesses = new Array();
  9895. this._postProcessesTakenIndices = [];
  9896. this._activeMeshes = new BABYLON.SmartArray(256);
  9897. this._globalPosition = BABYLON.Vector3.Zero();
  9898. scene.addCamera(this);
  9899. if (!scene.activeCamera) {
  9900. scene.activeCamera = this;
  9901. }
  9902. }
  9903. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9904. get: function () {
  9905. return Camera._PERSPECTIVE_CAMERA;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9911. get: function () {
  9912. return Camera._ORTHOGRAPHIC_CAMERA;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9918. get: function () {
  9919. return Camera._FOVMODE_VERTICAL_FIXED;
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9925. get: function () {
  9926. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9927. },
  9928. enumerable: true,
  9929. configurable: true
  9930. });
  9931. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9932. get: function () {
  9933. return Camera._RIG_MODE_NONE;
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9939. get: function () {
  9940. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9946. get: function () {
  9947. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9948. },
  9949. enumerable: true,
  9950. configurable: true
  9951. });
  9952. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9953. get: function () {
  9954. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9960. get: function () {
  9961. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9967. get: function () {
  9968. return Camera._RIG_MODE_VR;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. Object.defineProperty(Camera.prototype, "globalPosition", {
  9974. get: function () {
  9975. return this._globalPosition;
  9976. },
  9977. enumerable: true,
  9978. configurable: true
  9979. });
  9980. Camera.prototype.getActiveMeshes = function () {
  9981. return this._activeMeshes;
  9982. };
  9983. Camera.prototype.isActiveMesh = function (mesh) {
  9984. return (this._activeMeshes.indexOf(mesh) !== -1);
  9985. };
  9986. //Cache
  9987. Camera.prototype._initCache = function () {
  9988. _super.prototype._initCache.call(this);
  9989. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9990. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9991. this._cache.mode = undefined;
  9992. this._cache.minZ = undefined;
  9993. this._cache.maxZ = undefined;
  9994. this._cache.fov = undefined;
  9995. this._cache.aspectRatio = undefined;
  9996. this._cache.orthoLeft = undefined;
  9997. this._cache.orthoRight = undefined;
  9998. this._cache.orthoBottom = undefined;
  9999. this._cache.orthoTop = undefined;
  10000. this._cache.renderWidth = undefined;
  10001. this._cache.renderHeight = undefined;
  10002. };
  10003. Camera.prototype._updateCache = function (ignoreParentClass) {
  10004. if (!ignoreParentClass) {
  10005. _super.prototype._updateCache.call(this);
  10006. }
  10007. var engine = this.getEngine();
  10008. this._cache.position.copyFrom(this.position);
  10009. this._cache.upVector.copyFrom(this.upVector);
  10010. this._cache.mode = this.mode;
  10011. this._cache.minZ = this.minZ;
  10012. this._cache.maxZ = this.maxZ;
  10013. this._cache.fov = this.fov;
  10014. this._cache.aspectRatio = engine.getAspectRatio(this);
  10015. this._cache.orthoLeft = this.orthoLeft;
  10016. this._cache.orthoRight = this.orthoRight;
  10017. this._cache.orthoBottom = this.orthoBottom;
  10018. this._cache.orthoTop = this.orthoTop;
  10019. this._cache.renderWidth = engine.getRenderWidth();
  10020. this._cache.renderHeight = engine.getRenderHeight();
  10021. };
  10022. Camera.prototype._updateFromScene = function () {
  10023. this.updateCache();
  10024. this._update();
  10025. };
  10026. // Synchronized
  10027. Camera.prototype._isSynchronized = function () {
  10028. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10029. };
  10030. Camera.prototype._isSynchronizedViewMatrix = function () {
  10031. if (!_super.prototype._isSynchronized.call(this))
  10032. return false;
  10033. return this._cache.position.equals(this.position)
  10034. && this._cache.upVector.equals(this.upVector)
  10035. && this.isSynchronizedWithParent();
  10036. };
  10037. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10038. var check = this._cache.mode === this.mode
  10039. && this._cache.minZ === this.minZ
  10040. && this._cache.maxZ === this.maxZ;
  10041. if (!check) {
  10042. return false;
  10043. }
  10044. var engine = this.getEngine();
  10045. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10046. check = this._cache.fov === this.fov
  10047. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10048. }
  10049. else {
  10050. check = this._cache.orthoLeft === this.orthoLeft
  10051. && this._cache.orthoRight === this.orthoRight
  10052. && this._cache.orthoBottom === this.orthoBottom
  10053. && this._cache.orthoTop === this.orthoTop
  10054. && this._cache.renderWidth === engine.getRenderWidth()
  10055. && this._cache.renderHeight === engine.getRenderHeight();
  10056. }
  10057. return check;
  10058. };
  10059. // Controls
  10060. Camera.prototype.attachControl = function (element) {
  10061. };
  10062. Camera.prototype.detachControl = function (element) {
  10063. };
  10064. Camera.prototype._update = function () {
  10065. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10066. this._updateRigCameras();
  10067. }
  10068. this._checkInputs();
  10069. };
  10070. Camera.prototype._checkInputs = function () {
  10071. };
  10072. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10073. if (insertAt === void 0) { insertAt = null; }
  10074. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10075. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10076. return 0;
  10077. }
  10078. if (insertAt == null || insertAt < 0) {
  10079. this._postProcesses.push(postProcess);
  10080. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10081. return this._postProcesses.length - 1;
  10082. }
  10083. var add = 0;
  10084. if (this._postProcesses[insertAt]) {
  10085. var start = this._postProcesses.length - 1;
  10086. for (var i = start; i >= insertAt + 1; --i) {
  10087. this._postProcesses[i + 1] = this._postProcesses[i];
  10088. }
  10089. add = 1;
  10090. }
  10091. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10092. if (this._postProcessesTakenIndices[i] < insertAt) {
  10093. continue;
  10094. }
  10095. start = this._postProcessesTakenIndices.length - 1;
  10096. for (var j = start; j >= i; --j) {
  10097. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10098. }
  10099. this._postProcessesTakenIndices[i] = insertAt;
  10100. break;
  10101. }
  10102. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10103. this._postProcessesTakenIndices.push(insertAt);
  10104. }
  10105. var result = insertAt + add;
  10106. this._postProcesses[result] = postProcess;
  10107. return result;
  10108. };
  10109. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10110. if (atIndices === void 0) { atIndices = null; }
  10111. var result = [];
  10112. if (!atIndices) {
  10113. var length = this._postProcesses.length;
  10114. for (var i = 0; i < length; i++) {
  10115. if (this._postProcesses[i] !== postProcess) {
  10116. continue;
  10117. }
  10118. delete this._postProcesses[i];
  10119. var index = this._postProcessesTakenIndices.indexOf(i);
  10120. this._postProcessesTakenIndices.splice(index, 1);
  10121. }
  10122. }
  10123. else {
  10124. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10125. for (i = 0; i < atIndices.length; i++) {
  10126. var foundPostProcess = this._postProcesses[atIndices[i]];
  10127. if (foundPostProcess !== postProcess) {
  10128. result.push(i);
  10129. continue;
  10130. }
  10131. delete this._postProcesses[atIndices[i]];
  10132. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10133. this._postProcessesTakenIndices.splice(index, 1);
  10134. }
  10135. }
  10136. return result;
  10137. };
  10138. Camera.prototype.getWorldMatrix = function () {
  10139. if (!this._worldMatrix) {
  10140. this._worldMatrix = BABYLON.Matrix.Identity();
  10141. }
  10142. var viewMatrix = this.getViewMatrix();
  10143. viewMatrix.invertToRef(this._worldMatrix);
  10144. return this._worldMatrix;
  10145. };
  10146. Camera.prototype._getViewMatrix = function () {
  10147. return BABYLON.Matrix.Identity();
  10148. };
  10149. Camera.prototype.getViewMatrix = function (force) {
  10150. this._computedViewMatrix = this._computeViewMatrix(force);
  10151. if (!force && this._isSynchronizedViewMatrix()) {
  10152. return this._computedViewMatrix;
  10153. }
  10154. if (!this.parent || !this.parent.getWorldMatrix) {
  10155. this._globalPosition.copyFrom(this.position);
  10156. }
  10157. else {
  10158. if (!this._worldMatrix) {
  10159. this._worldMatrix = BABYLON.Matrix.Identity();
  10160. }
  10161. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10162. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10163. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10164. this._computedViewMatrix.invert();
  10165. this._markSyncedWithParent();
  10166. }
  10167. this._currentRenderId = this.getScene().getRenderId();
  10168. return this._computedViewMatrix;
  10169. };
  10170. Camera.prototype._computeViewMatrix = function (force) {
  10171. if (!force && this._isSynchronizedViewMatrix()) {
  10172. return this._computedViewMatrix;
  10173. }
  10174. this._computedViewMatrix = this._getViewMatrix();
  10175. this._currentRenderId = this.getScene().getRenderId();
  10176. return this._computedViewMatrix;
  10177. };
  10178. Camera.prototype.getProjectionMatrix = function (force) {
  10179. if (!force && this._isSynchronizedProjectionMatrix()) {
  10180. return this._projectionMatrix;
  10181. }
  10182. var engine = this.getEngine();
  10183. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10184. if (this.minZ <= 0) {
  10185. this.minZ = 0.1;
  10186. }
  10187. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10188. return this._projectionMatrix;
  10189. }
  10190. var halfWidth = engine.getRenderWidth() / 2.0;
  10191. var halfHeight = engine.getRenderHeight() / 2.0;
  10192. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10193. return this._projectionMatrix;
  10194. };
  10195. Camera.prototype.dispose = function () {
  10196. // Remove from scene
  10197. this.getScene().removeCamera(this);
  10198. while (this._rigCameras.length > 0) {
  10199. this._rigCameras.pop().dispose();
  10200. }
  10201. // Postprocesses
  10202. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10203. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10204. }
  10205. };
  10206. // ---- Camera rigs section ----
  10207. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10208. while (this._rigCameras.length > 0) {
  10209. this._rigCameras.pop().dispose();
  10210. }
  10211. this.cameraRigMode = mode;
  10212. this._cameraRigParams = {};
  10213. switch (this.cameraRigMode) {
  10214. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10215. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10216. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10217. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10218. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10219. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10220. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10221. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10222. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10223. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10224. break;
  10225. }
  10226. var postProcesses = new Array();
  10227. switch (this.cameraRigMode) {
  10228. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10229. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10230. this._rigCameras[0].isIntermediate = true;
  10231. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10232. postProcesses[1].onApply = function (effect) {
  10233. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10234. };
  10235. break;
  10236. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10237. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10238. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10239. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10240. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10241. var secondCamIndex = 1 - firstCamIndex;
  10242. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10243. this._rigCameras[firstCamIndex].isIntermediate = true;
  10244. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10245. break;
  10246. case Camera.RIG_MODE_VR:
  10247. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10248. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10249. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10250. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10251. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10252. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10253. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10254. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10255. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10256. if (metrics.compensateDistorsion) {
  10257. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10258. }
  10259. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10260. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10261. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10262. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10263. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10264. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10265. if (metrics.compensateDistorsion) {
  10266. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10267. }
  10268. break;
  10269. }
  10270. this._update();
  10271. };
  10272. Camera.prototype._getVRProjectionMatrix = function () {
  10273. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10274. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10275. return this._projectionMatrix;
  10276. };
  10277. Camera.prototype.setCameraRigParameter = function (name, value) {
  10278. this._cameraRigParams[name] = value;
  10279. //provisionnally:
  10280. if (name === "interaxialDistance") {
  10281. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10282. }
  10283. };
  10284. /**
  10285. * May needs to be overridden by children so sub has required properties to be copied
  10286. */
  10287. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10288. return null;
  10289. };
  10290. /**
  10291. * May needs to be overridden by children
  10292. */
  10293. Camera.prototype._updateRigCameras = function () {
  10294. for (var i = 0; i < this._rigCameras.length; i++) {
  10295. this._rigCameras[i].minZ = this.minZ;
  10296. this._rigCameras[i].maxZ = this.maxZ;
  10297. this._rigCameras[i].fov = this.fov;
  10298. }
  10299. // only update viewport when ANAGLYPH
  10300. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10301. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10302. }
  10303. };
  10304. // Statics
  10305. Camera._PERSPECTIVE_CAMERA = 0;
  10306. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10307. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10308. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10309. Camera._RIG_MODE_NONE = 0;
  10310. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10311. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10312. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10313. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10314. Camera._RIG_MODE_VR = 20;
  10315. return Camera;
  10316. })(BABYLON.Node);
  10317. BABYLON.Camera = Camera;
  10318. })(BABYLON || (BABYLON = {}));
  10319. var BABYLON;
  10320. (function (BABYLON) {
  10321. var TargetCamera = (function (_super) {
  10322. __extends(TargetCamera, _super);
  10323. function TargetCamera(name, position, scene) {
  10324. _super.call(this, name, position, scene);
  10325. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10326. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10327. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10328. this.speed = 2.0;
  10329. this.noRotationConstraint = false;
  10330. this.lockedTarget = null;
  10331. this._currentTarget = BABYLON.Vector3.Zero();
  10332. this._viewMatrix = BABYLON.Matrix.Zero();
  10333. this._camMatrix = BABYLON.Matrix.Zero();
  10334. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10335. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10336. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10337. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10338. this._lookAtTemp = BABYLON.Matrix.Zero();
  10339. this._tempMatrix = BABYLON.Matrix.Zero();
  10340. }
  10341. TargetCamera.prototype.getFrontPosition = function (distance) {
  10342. var direction = this.getTarget().subtract(this.position);
  10343. direction.normalize();
  10344. direction.scaleInPlace(distance);
  10345. return this.globalPosition.add(direction);
  10346. };
  10347. TargetCamera.prototype._getLockedTargetPosition = function () {
  10348. if (!this.lockedTarget) {
  10349. return null;
  10350. }
  10351. return this.lockedTarget.position || this.lockedTarget;
  10352. };
  10353. // Cache
  10354. TargetCamera.prototype._initCache = function () {
  10355. _super.prototype._initCache.call(this);
  10356. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10357. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10358. };
  10359. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10360. if (!ignoreParentClass) {
  10361. _super.prototype._updateCache.call(this);
  10362. }
  10363. var lockedTargetPosition = this._getLockedTargetPosition();
  10364. if (!lockedTargetPosition) {
  10365. this._cache.lockedTarget = null;
  10366. }
  10367. else {
  10368. if (!this._cache.lockedTarget) {
  10369. this._cache.lockedTarget = lockedTargetPosition.clone();
  10370. }
  10371. else {
  10372. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10373. }
  10374. }
  10375. this._cache.rotation.copyFrom(this.rotation);
  10376. };
  10377. // Synchronized
  10378. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10379. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10380. return false;
  10381. }
  10382. var lockedTargetPosition = this._getLockedTargetPosition();
  10383. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10384. && this._cache.rotation.equals(this.rotation);
  10385. };
  10386. // Methods
  10387. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10388. var engine = this.getEngine();
  10389. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10390. };
  10391. // Target
  10392. TargetCamera.prototype.setTarget = function (target) {
  10393. this.upVector.normalize();
  10394. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10395. this._camMatrix.invert();
  10396. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10397. var vDir = target.subtract(this.position);
  10398. if (vDir.x >= 0.0) {
  10399. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10400. }
  10401. else {
  10402. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10403. }
  10404. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10405. if (isNaN(this.rotation.x)) {
  10406. this.rotation.x = 0;
  10407. }
  10408. if (isNaN(this.rotation.y)) {
  10409. this.rotation.y = 0;
  10410. }
  10411. if (isNaN(this.rotation.z)) {
  10412. this.rotation.z = 0;
  10413. }
  10414. };
  10415. TargetCamera.prototype.getTarget = function () {
  10416. return this._currentTarget;
  10417. };
  10418. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10419. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10420. };
  10421. TargetCamera.prototype._updatePosition = function () {
  10422. this.position.addInPlace(this.cameraDirection);
  10423. };
  10424. TargetCamera.prototype._checkInputs = function () {
  10425. var needToMove = this._decideIfNeedsToMove();
  10426. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10427. // Move
  10428. if (needToMove) {
  10429. this._updatePosition();
  10430. }
  10431. // Rotate
  10432. if (needToRotate) {
  10433. this.rotation.x += this.cameraRotation.x;
  10434. this.rotation.y += this.cameraRotation.y;
  10435. if (!this.noRotationConstraint) {
  10436. var limit = (Math.PI / 2) * 0.95;
  10437. if (this.rotation.x > limit)
  10438. this.rotation.x = limit;
  10439. if (this.rotation.x < -limit)
  10440. this.rotation.x = -limit;
  10441. }
  10442. }
  10443. // Inertia
  10444. if (needToMove) {
  10445. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10446. this.cameraDirection.x = 0;
  10447. }
  10448. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10449. this.cameraDirection.y = 0;
  10450. }
  10451. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10452. this.cameraDirection.z = 0;
  10453. }
  10454. this.cameraDirection.scaleInPlace(this.inertia);
  10455. }
  10456. if (needToRotate) {
  10457. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10458. this.cameraRotation.x = 0;
  10459. }
  10460. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10461. this.cameraRotation.y = 0;
  10462. }
  10463. this.cameraRotation.scaleInPlace(this.inertia);
  10464. }
  10465. _super.prototype._checkInputs.call(this);
  10466. };
  10467. TargetCamera.prototype._getViewMatrix = function () {
  10468. if (!this.lockedTarget) {
  10469. // Compute
  10470. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10471. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10472. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10473. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10474. this._lookAtTemp.invert();
  10475. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10476. }
  10477. else {
  10478. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10479. }
  10480. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10481. // Computing target and final matrix
  10482. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10483. }
  10484. else {
  10485. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10486. }
  10487. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10488. return this._viewMatrix;
  10489. };
  10490. TargetCamera.prototype._getVRViewMatrix = function () {
  10491. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10492. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10493. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10494. // Computing target and final matrix
  10495. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10496. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10497. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10498. return this._viewMatrix;
  10499. };
  10500. /**
  10501. * @override
  10502. * Override Camera.createRigCamera
  10503. */
  10504. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10505. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10506. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10507. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10508. rigCamera._cameraRigParams = {};
  10509. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10510. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10511. }
  10512. return rigCamera;
  10513. }
  10514. return null;
  10515. };
  10516. /**
  10517. * @override
  10518. * Override Camera._updateRigCameras
  10519. */
  10520. TargetCamera.prototype._updateRigCameras = function () {
  10521. switch (this.cameraRigMode) {
  10522. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10524. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10525. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10526. case BABYLON.Camera.RIG_MODE_VR:
  10527. var camLeft = this._rigCameras[0];
  10528. var camRight = this._rigCameras[1];
  10529. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10530. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10531. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10532. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10533. camLeft.position.copyFrom(this.position);
  10534. camRight.position.copyFrom(this.position);
  10535. }
  10536. else {
  10537. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10538. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10539. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10540. camLeft.setTarget(this.getTarget());
  10541. camRight.setTarget(this.getTarget());
  10542. }
  10543. break;
  10544. }
  10545. _super.prototype._updateRigCameras.call(this);
  10546. };
  10547. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10548. if (!this._rigCamTransformMatrix) {
  10549. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10550. }
  10551. var target = this.getTarget();
  10552. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10553. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10554. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10555. };
  10556. return TargetCamera;
  10557. })(BABYLON.Camera);
  10558. BABYLON.TargetCamera = TargetCamera;
  10559. })(BABYLON || (BABYLON = {}));
  10560. var BABYLON;
  10561. (function (BABYLON) {
  10562. var FreeCamera = (function (_super) {
  10563. __extends(FreeCamera, _super);
  10564. function FreeCamera(name, position, scene) {
  10565. var _this = this;
  10566. _super.call(this, name, position, scene);
  10567. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10568. this.keysUp = [38];
  10569. this.keysDown = [40];
  10570. this.keysLeft = [37];
  10571. this.keysRight = [39];
  10572. this.checkCollisions = false;
  10573. this.applyGravity = false;
  10574. this.angularSensibility = 2000.0;
  10575. this._keys = [];
  10576. this._collider = new BABYLON.Collider();
  10577. this._needMoveForGravity = false;
  10578. this._oldPosition = BABYLON.Vector3.Zero();
  10579. this._diffPosition = BABYLON.Vector3.Zero();
  10580. this._newPosition = BABYLON.Vector3.Zero();
  10581. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10582. if (collidedMesh === void 0) { collidedMesh = null; }
  10583. //TODO move this to the collision coordinator!
  10584. if (_this.getScene().workerCollisions)
  10585. newPosition.multiplyInPlace(_this._collider.radius);
  10586. var updatePosition = function (newPos) {
  10587. _this._newPosition.copyFrom(newPos);
  10588. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10589. var oldPosition = _this.position.clone();
  10590. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10591. _this.position.addInPlace(_this._diffPosition);
  10592. if (_this.onCollide && collidedMesh) {
  10593. _this.onCollide(collidedMesh);
  10594. }
  10595. }
  10596. };
  10597. updatePosition(newPosition);
  10598. };
  10599. }
  10600. // Controls
  10601. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10602. var _this = this;
  10603. var previousPosition;
  10604. var engine = this.getEngine();
  10605. if (this._attachedElement) {
  10606. return;
  10607. }
  10608. this._attachedElement = element;
  10609. if (this._onMouseDown === undefined) {
  10610. this._onMouseDown = function (evt) {
  10611. previousPosition = {
  10612. x: evt.clientX,
  10613. y: evt.clientY
  10614. };
  10615. if (!noPreventDefault) {
  10616. evt.preventDefault();
  10617. }
  10618. };
  10619. this._onMouseUp = function (evt) {
  10620. previousPosition = null;
  10621. if (!noPreventDefault) {
  10622. evt.preventDefault();
  10623. }
  10624. };
  10625. this._onMouseOut = function (evt) {
  10626. previousPosition = null;
  10627. _this._keys = [];
  10628. if (!noPreventDefault) {
  10629. evt.preventDefault();
  10630. }
  10631. };
  10632. this._onMouseMove = function (evt) {
  10633. if (!previousPosition && !engine.isPointerLock) {
  10634. return;
  10635. }
  10636. var offsetX;
  10637. var offsetY;
  10638. if (!engine.isPointerLock) {
  10639. offsetX = evt.clientX - previousPosition.x;
  10640. offsetY = evt.clientY - previousPosition.y;
  10641. }
  10642. else {
  10643. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10644. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10645. }
  10646. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10647. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10648. previousPosition = {
  10649. x: evt.clientX,
  10650. y: evt.clientY
  10651. };
  10652. if (!noPreventDefault) {
  10653. evt.preventDefault();
  10654. }
  10655. };
  10656. this._onKeyDown = function (evt) {
  10657. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10658. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10659. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10660. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10661. var index = _this._keys.indexOf(evt.keyCode);
  10662. if (index === -1) {
  10663. _this._keys.push(evt.keyCode);
  10664. }
  10665. if (!noPreventDefault) {
  10666. evt.preventDefault();
  10667. }
  10668. }
  10669. };
  10670. this._onKeyUp = function (evt) {
  10671. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10672. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10673. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10674. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10675. var index = _this._keys.indexOf(evt.keyCode);
  10676. if (index >= 0) {
  10677. _this._keys.splice(index, 1);
  10678. }
  10679. if (!noPreventDefault) {
  10680. evt.preventDefault();
  10681. }
  10682. }
  10683. };
  10684. this._onLostFocus = function () {
  10685. _this._keys = [];
  10686. };
  10687. this._reset = function () {
  10688. _this._keys = [];
  10689. previousPosition = null;
  10690. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10691. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10692. };
  10693. }
  10694. element.addEventListener("mousedown", this._onMouseDown, false);
  10695. element.addEventListener("mouseup", this._onMouseUp, false);
  10696. element.addEventListener("mouseout", this._onMouseOut, false);
  10697. element.addEventListener("mousemove", this._onMouseMove, false);
  10698. BABYLON.Tools.RegisterTopRootEvents([
  10699. { name: "keydown", handler: this._onKeyDown },
  10700. { name: "keyup", handler: this._onKeyUp },
  10701. { name: "blur", handler: this._onLostFocus }
  10702. ]);
  10703. };
  10704. FreeCamera.prototype.detachControl = function (element) {
  10705. if (this._attachedElement != element) {
  10706. return;
  10707. }
  10708. element.removeEventListener("mousedown", this._onMouseDown);
  10709. element.removeEventListener("mouseup", this._onMouseUp);
  10710. element.removeEventListener("mouseout", this._onMouseOut);
  10711. element.removeEventListener("mousemove", this._onMouseMove);
  10712. BABYLON.Tools.UnregisterTopRootEvents([
  10713. { name: "keydown", handler: this._onKeyDown },
  10714. { name: "keyup", handler: this._onKeyUp },
  10715. { name: "blur", handler: this._onLostFocus }
  10716. ]);
  10717. this._attachedElement = null;
  10718. if (this._reset) {
  10719. this._reset();
  10720. }
  10721. };
  10722. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10723. var globalPosition;
  10724. if (this.parent) {
  10725. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10726. }
  10727. else {
  10728. globalPosition = this.position;
  10729. }
  10730. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10731. this._collider.radius = this.ellipsoid;
  10732. //add gravity to the velocity to prevent the dual-collision checking
  10733. if (this.applyGravity) {
  10734. velocity.addInPlace(this.getScene().gravity);
  10735. }
  10736. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10737. };
  10738. FreeCamera.prototype._checkInputs = function () {
  10739. if (!this._localDirection) {
  10740. this._localDirection = BABYLON.Vector3.Zero();
  10741. this._transformedDirection = BABYLON.Vector3.Zero();
  10742. }
  10743. // Keyboard
  10744. for (var index = 0; index < this._keys.length; index++) {
  10745. var keyCode = this._keys[index];
  10746. var speed = this._computeLocalCameraSpeed();
  10747. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10748. this._localDirection.copyFromFloats(-speed, 0, 0);
  10749. }
  10750. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10751. this._localDirection.copyFromFloats(0, 0, speed);
  10752. }
  10753. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10754. this._localDirection.copyFromFloats(speed, 0, 0);
  10755. }
  10756. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10757. this._localDirection.copyFromFloats(0, 0, -speed);
  10758. }
  10759. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10760. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10761. this.cameraDirection.addInPlace(this._transformedDirection);
  10762. }
  10763. _super.prototype._checkInputs.call(this);
  10764. };
  10765. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10766. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10767. };
  10768. FreeCamera.prototype._updatePosition = function () {
  10769. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10770. this._collideWithWorld(this.cameraDirection);
  10771. }
  10772. else {
  10773. this.position.addInPlace(this.cameraDirection);
  10774. }
  10775. };
  10776. return FreeCamera;
  10777. })(BABYLON.TargetCamera);
  10778. BABYLON.FreeCamera = FreeCamera;
  10779. })(BABYLON || (BABYLON = {}));
  10780. var BABYLON;
  10781. (function (BABYLON) {
  10782. var FollowCamera = (function (_super) {
  10783. __extends(FollowCamera, _super);
  10784. function FollowCamera(name, position, scene) {
  10785. _super.call(this, name, position, scene);
  10786. this.radius = 12;
  10787. this.rotationOffset = 0;
  10788. this.heightOffset = 4;
  10789. this.cameraAcceleration = 0.05;
  10790. this.maxCameraSpeed = 20;
  10791. }
  10792. FollowCamera.prototype.getRadians = function (degrees) {
  10793. return degrees * Math.PI / 180;
  10794. };
  10795. FollowCamera.prototype.follow = function (cameraTarget) {
  10796. if (!cameraTarget)
  10797. return;
  10798. var yRotation;
  10799. if (cameraTarget.rotationQuaternion) {
  10800. var rotMatrix = new BABYLON.Matrix();
  10801. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10802. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10803. }
  10804. else {
  10805. yRotation = cameraTarget.rotation.y;
  10806. }
  10807. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10808. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10809. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10810. var dx = targetX - this.position.x;
  10811. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10812. var dz = (targetZ) - this.position.z;
  10813. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10814. var vy = dy * this.cameraAcceleration;
  10815. var vz = dz * this.cameraAcceleration * 2;
  10816. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10817. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10818. }
  10819. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10820. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10821. }
  10822. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10823. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10824. }
  10825. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10826. this.setTarget(cameraTarget.position);
  10827. };
  10828. FollowCamera.prototype._checkInputs = function () {
  10829. _super.prototype._checkInputs.call(this);
  10830. this.follow(this.target);
  10831. };
  10832. return FollowCamera;
  10833. })(BABYLON.TargetCamera);
  10834. BABYLON.FollowCamera = FollowCamera;
  10835. var ArcFollowCamera = (function (_super) {
  10836. __extends(ArcFollowCamera, _super);
  10837. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10838. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10839. this.alpha = alpha;
  10840. this.beta = beta;
  10841. this.radius = radius;
  10842. this.target = target;
  10843. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10844. this.follow();
  10845. }
  10846. ArcFollowCamera.prototype.follow = function () {
  10847. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10848. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10849. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10850. this.position = this.target.position.add(this._cartesianCoordinates);
  10851. this.setTarget(this.target.position);
  10852. };
  10853. ArcFollowCamera.prototype._checkInputs = function () {
  10854. _super.prototype._checkInputs.call(this);
  10855. this.follow();
  10856. };
  10857. return ArcFollowCamera;
  10858. })(BABYLON.TargetCamera);
  10859. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10860. })(BABYLON || (BABYLON = {}));
  10861. var BABYLON;
  10862. (function (BABYLON) {
  10863. // We're mainly based on the logic defined into the FreeCamera code
  10864. var TouchCamera = (function (_super) {
  10865. __extends(TouchCamera, _super);
  10866. function TouchCamera(name, position, scene) {
  10867. _super.call(this, name, position, scene);
  10868. this._offsetX = null;
  10869. this._offsetY = null;
  10870. this._pointerCount = 0;
  10871. this._pointerPressed = [];
  10872. this.angularSensibility = 200000.0;
  10873. this.moveSensibility = 500.0;
  10874. }
  10875. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10876. var _this = this;
  10877. var previousPosition;
  10878. if (this._attachedCanvas) {
  10879. return;
  10880. }
  10881. this._attachedCanvas = canvas;
  10882. if (this._onPointerDown === undefined) {
  10883. this._onPointerDown = function (evt) {
  10884. if (!noPreventDefault) {
  10885. evt.preventDefault();
  10886. }
  10887. _this._pointerPressed.push(evt.pointerId);
  10888. if (_this._pointerPressed.length !== 1) {
  10889. return;
  10890. }
  10891. previousPosition = {
  10892. x: evt.clientX,
  10893. y: evt.clientY
  10894. };
  10895. };
  10896. this._onPointerUp = function (evt) {
  10897. if (!noPreventDefault) {
  10898. evt.preventDefault();
  10899. }
  10900. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10901. if (index === -1) {
  10902. return;
  10903. }
  10904. _this._pointerPressed.splice(index, 1);
  10905. if (index != 0) {
  10906. return;
  10907. }
  10908. previousPosition = null;
  10909. _this._offsetX = null;
  10910. _this._offsetY = null;
  10911. };
  10912. this._onPointerMove = function (evt) {
  10913. if (!noPreventDefault) {
  10914. evt.preventDefault();
  10915. }
  10916. if (!previousPosition) {
  10917. return;
  10918. }
  10919. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10920. if (index != 0) {
  10921. return;
  10922. }
  10923. _this._offsetX = evt.clientX - previousPosition.x;
  10924. _this._offsetY = -(evt.clientY - previousPosition.y);
  10925. };
  10926. this._onLostFocus = function () {
  10927. _this._offsetX = null;
  10928. _this._offsetY = null;
  10929. };
  10930. }
  10931. canvas.addEventListener("pointerdown", this._onPointerDown);
  10932. canvas.addEventListener("pointerup", this._onPointerUp);
  10933. canvas.addEventListener("pointerout", this._onPointerUp);
  10934. canvas.addEventListener("pointermove", this._onPointerMove);
  10935. BABYLON.Tools.RegisterTopRootEvents([
  10936. { name: "blur", handler: this._onLostFocus }
  10937. ]);
  10938. };
  10939. TouchCamera.prototype.detachControl = function (canvas) {
  10940. if (this._attachedCanvas != canvas) {
  10941. return;
  10942. }
  10943. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10944. canvas.removeEventListener("pointerup", this._onPointerUp);
  10945. canvas.removeEventListener("pointerout", this._onPointerUp);
  10946. canvas.removeEventListener("pointermove", this._onPointerMove);
  10947. BABYLON.Tools.UnregisterTopRootEvents([
  10948. { name: "blur", handler: this._onLostFocus }
  10949. ]);
  10950. this._attachedCanvas = null;
  10951. };
  10952. TouchCamera.prototype._checkInputs = function () {
  10953. if (this._offsetX) {
  10954. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10955. if (this._pointerPressed.length > 1) {
  10956. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10957. }
  10958. else {
  10959. var speed = this._computeLocalCameraSpeed();
  10960. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10961. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10962. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10963. }
  10964. }
  10965. _super.prototype._checkInputs.call(this);
  10966. };
  10967. return TouchCamera;
  10968. })(BABYLON.FreeCamera);
  10969. BABYLON.TouchCamera = TouchCamera;
  10970. })(BABYLON || (BABYLON = {}));
  10971. var BABYLON;
  10972. (function (BABYLON) {
  10973. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10974. var ArcRotateCamera = (function (_super) {
  10975. __extends(ArcRotateCamera, _super);
  10976. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10977. var _this = this;
  10978. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10979. this.alpha = alpha;
  10980. this.beta = beta;
  10981. this.radius = radius;
  10982. this.target = target;
  10983. this.inertialAlphaOffset = 0;
  10984. this.inertialBetaOffset = 0;
  10985. this.inertialRadiusOffset = 0;
  10986. this.lowerAlphaLimit = null;
  10987. this.upperAlphaLimit = null;
  10988. this.lowerBetaLimit = 0.01;
  10989. this.upperBetaLimit = Math.PI;
  10990. this.lowerRadiusLimit = null;
  10991. this.upperRadiusLimit = null;
  10992. this.angularSensibilityX = 1000.0;
  10993. this.angularSensibilityY = 1000.0;
  10994. this.wheelPrecision = 3.0;
  10995. this.pinchPrecision = 2.0;
  10996. this.panningSensibility = 50.0;
  10997. this.inertialPanningX = 0;
  10998. this.inertialPanningY = 0;
  10999. this.keysUp = [38];
  11000. this.keysDown = [40];
  11001. this.keysLeft = [37];
  11002. this.keysRight = [39];
  11003. this.zoomOnFactor = 1;
  11004. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11005. this.pinchInwards = true;
  11006. this.allowUpsideDown = true;
  11007. this._keys = [];
  11008. this._viewMatrix = new BABYLON.Matrix();
  11009. this._isRightClick = false;
  11010. this._isCtrlPushed = false;
  11011. this.checkCollisions = false;
  11012. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11013. this._collider = new BABYLON.Collider();
  11014. this._previousPosition = BABYLON.Vector3.Zero();
  11015. this._collisionVelocity = BABYLON.Vector3.Zero();
  11016. this._newPosition = BABYLON.Vector3.Zero();
  11017. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11018. if (collidedMesh === void 0) { collidedMesh = null; }
  11019. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11020. newPosition.multiplyInPlace(_this._collider.radius);
  11021. }
  11022. if (!collidedMesh) {
  11023. _this._previousPosition.copyFrom(_this.position);
  11024. }
  11025. else {
  11026. _this.setPosition(_this.position);
  11027. if (_this.onCollide) {
  11028. _this.onCollide(collidedMesh);
  11029. }
  11030. }
  11031. // Recompute because of constraints
  11032. var cosa = Math.cos(_this.alpha);
  11033. var sina = Math.sin(_this.alpha);
  11034. var cosb = Math.cos(_this.beta);
  11035. var sinb = Math.sin(_this.beta);
  11036. var target = _this._getTargetPosition();
  11037. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11038. _this.position.copyFrom(_this._newPosition);
  11039. var up = _this.upVector;
  11040. if (_this.allowUpsideDown && _this.beta < 0) {
  11041. var up = up.clone();
  11042. up = up.negate();
  11043. }
  11044. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11045. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11046. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11047. _this._collisionTriggered = false;
  11048. };
  11049. if (!this.target) {
  11050. this.target = BABYLON.Vector3.Zero();
  11051. }
  11052. this.getViewMatrix();
  11053. }
  11054. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11055. //deprecated angularSensibility support
  11056. get: function () {
  11057. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11058. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11059. },
  11060. //deprecated angularSensibility support
  11061. set: function (value) {
  11062. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11063. this.angularSensibilityX = value;
  11064. this.angularSensibilityY = value;
  11065. },
  11066. enumerable: true,
  11067. configurable: true
  11068. });
  11069. ArcRotateCamera.prototype._getTargetPosition = function () {
  11070. return this.target.position || this.target;
  11071. };
  11072. // Cache
  11073. ArcRotateCamera.prototype._initCache = function () {
  11074. _super.prototype._initCache.call(this);
  11075. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11076. this._cache.alpha = undefined;
  11077. this._cache.beta = undefined;
  11078. this._cache.radius = undefined;
  11079. this._cache.targetScreenOffset = undefined;
  11080. };
  11081. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11082. if (!ignoreParentClass) {
  11083. _super.prototype._updateCache.call(this);
  11084. }
  11085. this._cache.target.copyFrom(this._getTargetPosition());
  11086. this._cache.alpha = this.alpha;
  11087. this._cache.beta = this.beta;
  11088. this._cache.radius = this.radius;
  11089. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11090. };
  11091. // Synchronized
  11092. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11093. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11094. return false;
  11095. return this._cache.target.equals(this._getTargetPosition())
  11096. && this._cache.alpha === this.alpha
  11097. && this._cache.beta === this.beta
  11098. && this._cache.radius === this.radius
  11099. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11100. };
  11101. // Methods
  11102. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11103. var _this = this;
  11104. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11105. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11106. var previousPinchDistance = 0;
  11107. var pointers = new BABYLON.SmartCollection();
  11108. if (this._attachedElement) {
  11109. return;
  11110. }
  11111. this._attachedElement = element;
  11112. var engine = this.getEngine();
  11113. if (this._onPointerDown === undefined) {
  11114. this._onPointerDown = function (evt) {
  11115. // Manage panning with right click
  11116. _this._isRightClick = evt.button === 2 ? true : false;
  11117. // manage pointers
  11118. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11119. cacheSoloPointer = pointers.item(evt.pointerId);
  11120. if (!noPreventDefault) {
  11121. evt.preventDefault();
  11122. }
  11123. };
  11124. this._onPointerUp = function (evt) {
  11125. cacheSoloPointer = null;
  11126. previousPinchDistance = 0;
  11127. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11128. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11129. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11130. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11131. pointers.empty();
  11132. if (!noPreventDefault) {
  11133. evt.preventDefault();
  11134. }
  11135. };
  11136. this._onContextMenu = function (evt) {
  11137. evt.preventDefault();
  11138. };
  11139. this._onPointerMove = function (evt) {
  11140. if (!noPreventDefault) {
  11141. evt.preventDefault();
  11142. }
  11143. switch (pointers.count) {
  11144. case 1:
  11145. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11146. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11147. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11148. }
  11149. else {
  11150. var offsetX = evt.clientX - cacheSoloPointer.x;
  11151. var offsetY = evt.clientY - cacheSoloPointer.y;
  11152. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11153. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11154. }
  11155. cacheSoloPointer.x = evt.clientX;
  11156. cacheSoloPointer.y = evt.clientY;
  11157. break;
  11158. case 2:
  11159. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11160. pointers.item(evt.pointerId).x = evt.clientX;
  11161. pointers.item(evt.pointerId).y = evt.clientY;
  11162. var direction = _this.pinchInwards ? 1 : -1;
  11163. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11164. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11165. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11166. if (previousPinchDistance === 0) {
  11167. previousPinchDistance = pinchSquaredDistance;
  11168. return;
  11169. }
  11170. if (pinchSquaredDistance !== previousPinchDistance) {
  11171. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11172. previousPinchDistance = pinchSquaredDistance;
  11173. }
  11174. break;
  11175. default:
  11176. if (pointers.item(evt.pointerId)) {
  11177. pointers.item(evt.pointerId).x = evt.clientX;
  11178. pointers.item(evt.pointerId).y = evt.clientY;
  11179. }
  11180. }
  11181. };
  11182. this._onMouseMove = function (evt) {
  11183. if (!engine.isPointerLock) {
  11184. return;
  11185. }
  11186. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11187. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11188. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11189. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11190. if (!noPreventDefault) {
  11191. evt.preventDefault();
  11192. }
  11193. };
  11194. this._wheel = function (event) {
  11195. var delta = 0;
  11196. if (event.wheelDelta) {
  11197. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11198. }
  11199. else if (event.detail) {
  11200. delta = -event.detail / _this.wheelPrecision;
  11201. }
  11202. if (delta)
  11203. _this.inertialRadiusOffset += delta;
  11204. if (event.preventDefault) {
  11205. if (!noPreventDefault) {
  11206. event.preventDefault();
  11207. }
  11208. }
  11209. };
  11210. this._onKeyDown = function (evt) {
  11211. _this._isCtrlPushed = evt.ctrlKey;
  11212. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11213. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11214. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11215. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11216. var index = _this._keys.indexOf(evt.keyCode);
  11217. if (index === -1) {
  11218. _this._keys.push(evt.keyCode);
  11219. }
  11220. if (evt.preventDefault) {
  11221. if (!noPreventDefault) {
  11222. evt.preventDefault();
  11223. }
  11224. }
  11225. }
  11226. };
  11227. this._onKeyUp = function (evt) {
  11228. _this._isCtrlPushed = evt.ctrlKey;
  11229. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11230. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11231. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11232. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11233. var index = _this._keys.indexOf(evt.keyCode);
  11234. if (index >= 0) {
  11235. _this._keys.splice(index, 1);
  11236. }
  11237. if (evt.preventDefault) {
  11238. if (!noPreventDefault) {
  11239. evt.preventDefault();
  11240. }
  11241. }
  11242. }
  11243. };
  11244. this._onLostFocus = function () {
  11245. _this._keys = [];
  11246. pointers.empty();
  11247. previousPinchDistance = 0;
  11248. cacheSoloPointer = null;
  11249. };
  11250. this._onGestureStart = function (e) {
  11251. if (window.MSGesture === undefined) {
  11252. return;
  11253. }
  11254. if (!_this._MSGestureHandler) {
  11255. _this._MSGestureHandler = new MSGesture();
  11256. _this._MSGestureHandler.target = element;
  11257. }
  11258. _this._MSGestureHandler.addPointer(e.pointerId);
  11259. };
  11260. this._onGesture = function (e) {
  11261. _this.radius *= e.scale;
  11262. if (e.preventDefault) {
  11263. if (!noPreventDefault) {
  11264. e.stopPropagation();
  11265. e.preventDefault();
  11266. }
  11267. }
  11268. };
  11269. this._reset = function () {
  11270. _this._keys = [];
  11271. _this.inertialAlphaOffset = 0;
  11272. _this.inertialBetaOffset = 0;
  11273. _this.inertialRadiusOffset = 0;
  11274. pointers.empty();
  11275. previousPinchDistance = 0;
  11276. cacheSoloPointer = null;
  11277. };
  11278. }
  11279. if (!useCtrlForPanning) {
  11280. element.addEventListener("contextmenu", this._onContextMenu, false);
  11281. }
  11282. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11283. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11284. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11285. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11286. element.addEventListener("mousemove", this._onMouseMove, false);
  11287. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11288. element.addEventListener("MSGestureChange", this._onGesture, false);
  11289. element.addEventListener('mousewheel', this._wheel, false);
  11290. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11291. BABYLON.Tools.RegisterTopRootEvents([
  11292. { name: "keydown", handler: this._onKeyDown },
  11293. { name: "keyup", handler: this._onKeyUp },
  11294. { name: "blur", handler: this._onLostFocus }
  11295. ]);
  11296. };
  11297. ArcRotateCamera.prototype.detachControl = function (element) {
  11298. if (this._attachedElement !== element) {
  11299. return;
  11300. }
  11301. element.removeEventListener("contextmenu", this._onContextMenu);
  11302. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11303. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11304. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11305. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11306. element.removeEventListener("mousemove", this._onMouseMove);
  11307. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11308. element.removeEventListener("MSGestureChange", this._onGesture);
  11309. element.removeEventListener('mousewheel', this._wheel);
  11310. element.removeEventListener('DOMMouseScroll', this._wheel);
  11311. BABYLON.Tools.UnregisterTopRootEvents([
  11312. { name: "keydown", handler: this._onKeyDown },
  11313. { name: "keyup", handler: this._onKeyUp },
  11314. { name: "blur", handler: this._onLostFocus }
  11315. ]);
  11316. this._MSGestureHandler = null;
  11317. this._attachedElement = null;
  11318. if (this._reset) {
  11319. this._reset();
  11320. }
  11321. };
  11322. ArcRotateCamera.prototype._checkInputs = function () {
  11323. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11324. if (this._collisionTriggered) {
  11325. return;
  11326. }
  11327. // Keyboard
  11328. for (var index = 0; index < this._keys.length; index++) {
  11329. var keyCode = this._keys[index];
  11330. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11331. this.inertialAlphaOffset -= 0.01;
  11332. }
  11333. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11334. this.inertialBetaOffset -= 0.01;
  11335. }
  11336. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11337. this.inertialAlphaOffset += 0.01;
  11338. }
  11339. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11340. this.inertialBetaOffset += 0.01;
  11341. }
  11342. }
  11343. // Inertia
  11344. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11345. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11346. this.beta += this.inertialBetaOffset;
  11347. this.radius -= this.inertialRadiusOffset;
  11348. this.inertialAlphaOffset *= this.inertia;
  11349. this.inertialBetaOffset *= this.inertia;
  11350. this.inertialRadiusOffset *= this.inertia;
  11351. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11352. this.inertialAlphaOffset = 0;
  11353. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11354. this.inertialBetaOffset = 0;
  11355. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11356. this.inertialRadiusOffset = 0;
  11357. }
  11358. // Panning inertia
  11359. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11360. if (!this._localDirection) {
  11361. this._localDirection = BABYLON.Vector3.Zero();
  11362. this._transformedDirection = BABYLON.Vector3.Zero();
  11363. }
  11364. this.inertialPanningX *= this.inertia;
  11365. this.inertialPanningY *= this.inertia;
  11366. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11367. this.inertialPanningX = 0;
  11368. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11369. this.inertialPanningY = 0;
  11370. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11371. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11372. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11373. this.target.addInPlace(this._transformedDirection);
  11374. }
  11375. // Limits
  11376. this._checkLimits();
  11377. _super.prototype._checkInputs.call(this);
  11378. };
  11379. ArcRotateCamera.prototype._checkLimits = function () {
  11380. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11381. if (this.allowUpsideDown && this.beta > Math.PI) {
  11382. this.beta = this.beta - (2 * Math.PI);
  11383. }
  11384. }
  11385. else {
  11386. if (this.beta < this.lowerBetaLimit) {
  11387. this.beta = this.lowerBetaLimit;
  11388. }
  11389. }
  11390. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11391. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11392. this.beta = this.beta + (2 * Math.PI);
  11393. }
  11394. }
  11395. else {
  11396. if (this.beta > this.upperBetaLimit) {
  11397. this.beta = this.upperBetaLimit;
  11398. }
  11399. }
  11400. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11401. this.alpha = this.lowerAlphaLimit;
  11402. }
  11403. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11404. this.alpha = this.upperAlphaLimit;
  11405. }
  11406. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11407. this.radius = this.lowerRadiusLimit;
  11408. }
  11409. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11410. this.radius = this.upperRadiusLimit;
  11411. }
  11412. };
  11413. ArcRotateCamera.prototype.setPosition = function (position) {
  11414. var radiusv3 = position.subtract(this._getTargetPosition());
  11415. this.radius = radiusv3.length();
  11416. // Alpha
  11417. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11418. if (radiusv3.z < 0) {
  11419. this.alpha = 2 * Math.PI - this.alpha;
  11420. }
  11421. // Beta
  11422. this.beta = Math.acos(radiusv3.y / this.radius);
  11423. this._checkLimits();
  11424. };
  11425. ArcRotateCamera.prototype.setTarget = function (target) {
  11426. this.target = target;
  11427. };
  11428. ArcRotateCamera.prototype._getViewMatrix = function () {
  11429. // Compute
  11430. var cosa = Math.cos(this.alpha);
  11431. var sina = Math.sin(this.alpha);
  11432. var cosb = Math.cos(this.beta);
  11433. var sinb = Math.sin(this.beta);
  11434. var target = this._getTargetPosition();
  11435. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11436. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11437. this._collider.radius = this.collisionRadius;
  11438. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11439. this._collisionTriggered = true;
  11440. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11441. }
  11442. else {
  11443. this.position.copyFrom(this._newPosition);
  11444. var up = this.upVector;
  11445. if (this.allowUpsideDown && this.beta < 0) {
  11446. var up = up.clone();
  11447. up = up.negate();
  11448. }
  11449. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11450. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11451. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11452. }
  11453. return this._viewMatrix;
  11454. };
  11455. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11456. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11457. meshes = meshes || this.getScene().meshes;
  11458. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11459. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11460. this.radius = distance * this.zoomOnFactor;
  11461. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11462. };
  11463. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11464. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11465. var meshesOrMinMaxVector;
  11466. var distance;
  11467. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11468. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11469. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11470. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11471. }
  11472. else {
  11473. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11474. distance = meshesOrMinMaxVectorAndDistance.distance;
  11475. }
  11476. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11477. if (!doNotUpdateMaxZ) {
  11478. this.maxZ = distance * 2;
  11479. }
  11480. };
  11481. /**
  11482. * @override
  11483. * Override Camera.createRigCamera
  11484. */
  11485. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11486. switch (this.cameraRigMode) {
  11487. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11489. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11491. case BABYLON.Camera.RIG_MODE_VR:
  11492. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11493. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11494. }
  11495. };
  11496. /**
  11497. * @override
  11498. * Override Camera._updateRigCameras
  11499. */
  11500. ArcRotateCamera.prototype._updateRigCameras = function () {
  11501. switch (this.cameraRigMode) {
  11502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11503. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11504. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11505. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11506. case BABYLON.Camera.RIG_MODE_VR:
  11507. var camLeft = this._rigCameras[0];
  11508. var camRight = this._rigCameras[1];
  11509. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11510. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11511. camLeft.beta = camRight.beta = this.beta;
  11512. camLeft.radius = camRight.radius = this.radius;
  11513. break;
  11514. }
  11515. _super.prototype._updateRigCameras.call(this);
  11516. };
  11517. return ArcRotateCamera;
  11518. })(BABYLON.TargetCamera);
  11519. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11520. })(BABYLON || (BABYLON = {}));
  11521. var BABYLON;
  11522. (function (BABYLON) {
  11523. // We're mainly based on the logic defined into the FreeCamera code
  11524. var DeviceOrientationCamera = (function (_super) {
  11525. __extends(DeviceOrientationCamera, _super);
  11526. function DeviceOrientationCamera(name, position, scene) {
  11527. var _this = this;
  11528. _super.call(this, name, position, scene);
  11529. this._offsetX = null;
  11530. this._offsetY = null;
  11531. this._orientationGamma = 0;
  11532. this._orientationBeta = 0;
  11533. this._initialOrientationGamma = 0;
  11534. this._initialOrientationBeta = 0;
  11535. this.angularSensibility = 10000.0;
  11536. this.moveSensibility = 50.0;
  11537. window.addEventListener("resize", function () {
  11538. _this._initialOrientationGamma = null;
  11539. }, false);
  11540. }
  11541. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11542. var _this = this;
  11543. if (this._attachedCanvas) {
  11544. return;
  11545. }
  11546. this._attachedCanvas = canvas;
  11547. if (!this._orientationChanged) {
  11548. this._orientationChanged = function (evt) {
  11549. if (!_this._initialOrientationGamma) {
  11550. _this._initialOrientationGamma = evt.gamma;
  11551. _this._initialOrientationBeta = evt.beta;
  11552. }
  11553. _this._orientationGamma = evt.gamma;
  11554. _this._orientationBeta = evt.beta;
  11555. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11556. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11557. };
  11558. }
  11559. window.addEventListener("deviceorientation", this._orientationChanged);
  11560. };
  11561. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11562. if (this._attachedCanvas != canvas) {
  11563. return;
  11564. }
  11565. window.removeEventListener("deviceorientation", this._orientationChanged);
  11566. this._attachedCanvas = null;
  11567. this._orientationGamma = 0;
  11568. this._orientationBeta = 0;
  11569. this._initialOrientationGamma = 0;
  11570. this._initialOrientationBeta = 0;
  11571. };
  11572. DeviceOrientationCamera.prototype._checkInputs = function () {
  11573. if (!this._offsetX) {
  11574. return;
  11575. }
  11576. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11577. var speed = this._computeLocalCameraSpeed();
  11578. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11579. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11580. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11581. _super.prototype._checkInputs.call(this);
  11582. };
  11583. return DeviceOrientationCamera;
  11584. })(BABYLON.FreeCamera);
  11585. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11586. })(BABYLON || (BABYLON = {}));
  11587. var BABYLON;
  11588. (function (BABYLON) {
  11589. var Gamepads = (function () {
  11590. function Gamepads(ongamedpadconnected) {
  11591. var _this = this;
  11592. this.babylonGamepads = [];
  11593. this.oneGamepadConnected = false;
  11594. this.isMonitoring = false;
  11595. this.gamepadEventSupported = 'GamepadEvent' in window;
  11596. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11597. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11598. 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=";
  11599. this._callbackGamepadConnected = ongamedpadconnected;
  11600. if (this.gamepadSupportAvailable) {
  11601. // Checking if the gamepad connected event is supported (like in Firefox)
  11602. if (this.gamepadEventSupported) {
  11603. window.addEventListener('gamepadconnected', function (evt) {
  11604. _this._onGamepadConnected(evt);
  11605. }, false);
  11606. window.addEventListener('gamepaddisconnected', function (evt) {
  11607. _this._onGamepadDisconnected(evt);
  11608. }, false);
  11609. }
  11610. else {
  11611. this._startMonitoringGamepads();
  11612. }
  11613. if (!this.oneGamepadConnected) {
  11614. this._insertGamepadDOMInstructions();
  11615. }
  11616. }
  11617. else {
  11618. this._insertGamepadDOMNotSupported();
  11619. }
  11620. }
  11621. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11622. Gamepads.gamepadDOMInfo = document.createElement("div");
  11623. var buttonAImage = document.createElement("img");
  11624. buttonAImage.src = this.buttonADataURL;
  11625. var spanMessage = document.createElement("span");
  11626. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11627. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11628. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11629. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11630. Gamepads.gamepadDOMInfo.style.width = "100%";
  11631. Gamepads.gamepadDOMInfo.style.height = "48px";
  11632. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11633. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11634. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11635. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11636. buttonAImage.style.position = "relative";
  11637. buttonAImage.style.bottom = "8px";
  11638. spanMessage.style.position = "relative";
  11639. spanMessage.style.fontSize = "32px";
  11640. spanMessage.style.bottom = "32px";
  11641. spanMessage.style.color = "green";
  11642. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11643. };
  11644. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11645. Gamepads.gamepadDOMInfo = document.createElement("div");
  11646. var spanMessage = document.createElement("span");
  11647. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11648. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11649. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11650. Gamepads.gamepadDOMInfo.style.width = "100%";
  11651. Gamepads.gamepadDOMInfo.style.height = "40px";
  11652. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11653. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11654. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11655. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11656. spanMessage.style.position = "relative";
  11657. spanMessage.style.fontSize = "32px";
  11658. spanMessage.style.color = "red";
  11659. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11660. };
  11661. Gamepads.prototype.dispose = function () {
  11662. if (Gamepads.gamepadDOMInfo) {
  11663. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11664. }
  11665. };
  11666. Gamepads.prototype._onGamepadConnected = function (evt) {
  11667. var newGamepad = this._addNewGamepad(evt.gamepad);
  11668. if (this._callbackGamepadConnected)
  11669. this._callbackGamepadConnected(newGamepad);
  11670. this._startMonitoringGamepads();
  11671. };
  11672. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11673. if (!this.oneGamepadConnected) {
  11674. this.oneGamepadConnected = true;
  11675. if (Gamepads.gamepadDOMInfo) {
  11676. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11677. Gamepads.gamepadDOMInfo = null;
  11678. }
  11679. }
  11680. var newGamepad;
  11681. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11682. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11683. }
  11684. else {
  11685. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11686. }
  11687. this.babylonGamepads.push(newGamepad);
  11688. return newGamepad;
  11689. };
  11690. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11691. // Remove the gamepad from the list of gamepads to monitor.
  11692. for (var i in this.babylonGamepads) {
  11693. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11694. this.babylonGamepads.splice(i, 1);
  11695. break;
  11696. }
  11697. }
  11698. // If no gamepads are left, stop the polling loop.
  11699. if (this.babylonGamepads.length == 0) {
  11700. this._stopMonitoringGamepads();
  11701. }
  11702. };
  11703. Gamepads.prototype._startMonitoringGamepads = function () {
  11704. if (!this.isMonitoring) {
  11705. this.isMonitoring = true;
  11706. this._checkGamepadsStatus();
  11707. }
  11708. };
  11709. Gamepads.prototype._stopMonitoringGamepads = function () {
  11710. this.isMonitoring = false;
  11711. };
  11712. Gamepads.prototype._checkGamepadsStatus = function () {
  11713. var _this = this;
  11714. // updating gamepad objects
  11715. this._updateGamepadObjects();
  11716. for (var i in this.babylonGamepads) {
  11717. this.babylonGamepads[i].update();
  11718. }
  11719. if (this.isMonitoring) {
  11720. if (window.requestAnimationFrame) {
  11721. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11722. }
  11723. else if (window.mozRequestAnimationFrame) {
  11724. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11725. }
  11726. else if (window.webkitRequestAnimationFrame) {
  11727. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11728. }
  11729. }
  11730. };
  11731. // This function is called only on Chrome, which does not yet support
  11732. // connection/disconnection events, but requires you to monitor
  11733. // an array for changes.
  11734. Gamepads.prototype._updateGamepadObjects = function () {
  11735. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11736. for (var i = 0; i < gamepads.length; i++) {
  11737. if (gamepads[i]) {
  11738. if (!(gamepads[i].index in this.babylonGamepads)) {
  11739. var newGamepad = this._addNewGamepad(gamepads[i]);
  11740. if (this._callbackGamepadConnected) {
  11741. this._callbackGamepadConnected(newGamepad);
  11742. }
  11743. }
  11744. else {
  11745. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11746. }
  11747. }
  11748. }
  11749. };
  11750. return Gamepads;
  11751. })();
  11752. BABYLON.Gamepads = Gamepads;
  11753. var StickValues = (function () {
  11754. function StickValues(x, y) {
  11755. this.x = x;
  11756. this.y = y;
  11757. }
  11758. return StickValues;
  11759. })();
  11760. BABYLON.StickValues = StickValues;
  11761. var Gamepad = (function () {
  11762. function Gamepad(id, index, browserGamepad) {
  11763. this.id = id;
  11764. this.index = index;
  11765. this.browserGamepad = browserGamepad;
  11766. if (this.browserGamepad.axes.length >= 2) {
  11767. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11768. }
  11769. if (this.browserGamepad.axes.length >= 4) {
  11770. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11771. }
  11772. }
  11773. Gamepad.prototype.onleftstickchanged = function (callback) {
  11774. this._onleftstickchanged = callback;
  11775. };
  11776. Gamepad.prototype.onrightstickchanged = function (callback) {
  11777. this._onrightstickchanged = callback;
  11778. };
  11779. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11780. get: function () {
  11781. return this._leftStick;
  11782. },
  11783. set: function (newValues) {
  11784. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11785. this._onleftstickchanged(newValues);
  11786. }
  11787. this._leftStick = newValues;
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11793. get: function () {
  11794. return this._rightStick;
  11795. },
  11796. set: function (newValues) {
  11797. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11798. this._onrightstickchanged(newValues);
  11799. }
  11800. this._rightStick = newValues;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Gamepad.prototype.update = function () {
  11806. if (this._leftStick) {
  11807. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11808. }
  11809. if (this._rightStick) {
  11810. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11811. }
  11812. };
  11813. return Gamepad;
  11814. })();
  11815. BABYLON.Gamepad = Gamepad;
  11816. var GenericPad = (function (_super) {
  11817. __extends(GenericPad, _super);
  11818. function GenericPad(id, index, gamepad) {
  11819. _super.call(this, id, index, gamepad);
  11820. this.id = id;
  11821. this.index = index;
  11822. this.gamepad = gamepad;
  11823. this._buttons = new Array(gamepad.buttons.length);
  11824. }
  11825. GenericPad.prototype.onbuttondown = function (callback) {
  11826. this._onbuttondown = callback;
  11827. };
  11828. GenericPad.prototype.onbuttonup = function (callback) {
  11829. this._onbuttonup = callback;
  11830. };
  11831. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11832. if (newValue !== currentValue) {
  11833. if (this._onbuttondown && newValue === 1) {
  11834. this._onbuttondown(buttonIndex);
  11835. }
  11836. if (this._onbuttonup && newValue === 0) {
  11837. this._onbuttonup(buttonIndex);
  11838. }
  11839. }
  11840. return newValue;
  11841. };
  11842. GenericPad.prototype.update = function () {
  11843. _super.prototype.update.call(this);
  11844. for (var index = 0; index < this._buttons.length; index++) {
  11845. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11846. }
  11847. };
  11848. return GenericPad;
  11849. })(Gamepad);
  11850. BABYLON.GenericPad = GenericPad;
  11851. (function (Xbox360Button) {
  11852. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11853. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11854. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11855. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11856. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11857. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11858. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11859. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11860. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11861. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11862. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11863. var Xbox360Button = BABYLON.Xbox360Button;
  11864. (function (Xbox360Dpad) {
  11865. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11866. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11867. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11868. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11869. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11870. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11871. var Xbox360Pad = (function (_super) {
  11872. __extends(Xbox360Pad, _super);
  11873. function Xbox360Pad() {
  11874. _super.apply(this, arguments);
  11875. this._leftTrigger = 0;
  11876. this._rightTrigger = 0;
  11877. this._buttonA = 0;
  11878. this._buttonB = 0;
  11879. this._buttonX = 0;
  11880. this._buttonY = 0;
  11881. this._buttonBack = 0;
  11882. this._buttonStart = 0;
  11883. this._buttonLB = 0;
  11884. this._buttonRB = 0;
  11885. this._buttonLeftStick = 0;
  11886. this._buttonRightStick = 0;
  11887. this._dPadUp = 0;
  11888. this._dPadDown = 0;
  11889. this._dPadLeft = 0;
  11890. this._dPadRight = 0;
  11891. }
  11892. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11893. this._onlefttriggerchanged = callback;
  11894. };
  11895. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11896. this._onrighttriggerchanged = callback;
  11897. };
  11898. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11899. get: function () {
  11900. return this._leftTrigger;
  11901. },
  11902. set: function (newValue) {
  11903. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11904. this._onlefttriggerchanged(newValue);
  11905. }
  11906. this._leftTrigger = newValue;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11912. get: function () {
  11913. return this._rightTrigger;
  11914. },
  11915. set: function (newValue) {
  11916. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11917. this._onrighttriggerchanged(newValue);
  11918. }
  11919. this._rightTrigger = newValue;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11925. this._onbuttondown = callback;
  11926. };
  11927. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11928. this._onbuttonup = callback;
  11929. };
  11930. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11931. this._ondpaddown = callback;
  11932. };
  11933. Xbox360Pad.prototype.ondpadup = function (callback) {
  11934. this._ondpadup = callback;
  11935. };
  11936. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11937. if (newValue !== currentValue) {
  11938. if (this._onbuttondown && newValue === 1) {
  11939. this._onbuttondown(buttonType);
  11940. }
  11941. if (this._onbuttonup && newValue === 0) {
  11942. this._onbuttonup(buttonType);
  11943. }
  11944. }
  11945. return newValue;
  11946. };
  11947. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11948. if (newValue !== currentValue) {
  11949. if (this._ondpaddown && newValue === 1) {
  11950. this._ondpaddown(buttonType);
  11951. }
  11952. if (this._ondpadup && newValue === 0) {
  11953. this._ondpadup(buttonType);
  11954. }
  11955. }
  11956. return newValue;
  11957. };
  11958. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11959. get: function () {
  11960. return this._buttonA;
  11961. },
  11962. set: function (value) {
  11963. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11969. get: function () {
  11970. return this._buttonB;
  11971. },
  11972. set: function (value) {
  11973. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11979. get: function () {
  11980. return this._buttonX;
  11981. },
  11982. set: function (value) {
  11983. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11989. get: function () {
  11990. return this._buttonY;
  11991. },
  11992. set: function (value) {
  11993. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11994. },
  11995. enumerable: true,
  11996. configurable: true
  11997. });
  11998. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11999. get: function () {
  12000. return this._buttonStart;
  12001. },
  12002. set: function (value) {
  12003. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12009. get: function () {
  12010. return this._buttonBack;
  12011. },
  12012. set: function (value) {
  12013. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12019. get: function () {
  12020. return this._buttonLB;
  12021. },
  12022. set: function (value) {
  12023. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12029. get: function () {
  12030. return this._buttonRB;
  12031. },
  12032. set: function (value) {
  12033. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12039. get: function () {
  12040. return this._buttonLeftStick;
  12041. },
  12042. set: function (value) {
  12043. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12049. get: function () {
  12050. return this._buttonRightStick;
  12051. },
  12052. set: function (value) {
  12053. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12054. },
  12055. enumerable: true,
  12056. configurable: true
  12057. });
  12058. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12059. get: function () {
  12060. return this._dPadUp;
  12061. },
  12062. set: function (value) {
  12063. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12069. get: function () {
  12070. return this._dPadDown;
  12071. },
  12072. set: function (value) {
  12073. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12079. get: function () {
  12080. return this._dPadLeft;
  12081. },
  12082. set: function (value) {
  12083. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12084. },
  12085. enumerable: true,
  12086. configurable: true
  12087. });
  12088. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12089. get: function () {
  12090. return this._dPadRight;
  12091. },
  12092. set: function (value) {
  12093. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12094. },
  12095. enumerable: true,
  12096. configurable: true
  12097. });
  12098. Xbox360Pad.prototype.update = function () {
  12099. _super.prototype.update.call(this);
  12100. this.buttonA = this.browserGamepad.buttons[0].value;
  12101. this.buttonB = this.browserGamepad.buttons[1].value;
  12102. this.buttonX = this.browserGamepad.buttons[2].value;
  12103. this.buttonY = this.browserGamepad.buttons[3].value;
  12104. this.buttonLB = this.browserGamepad.buttons[4].value;
  12105. this.buttonRB = this.browserGamepad.buttons[5].value;
  12106. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12107. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12108. this.buttonBack = this.browserGamepad.buttons[8].value;
  12109. this.buttonStart = this.browserGamepad.buttons[9].value;
  12110. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12111. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12112. this.dPadUp = this.browserGamepad.buttons[12].value;
  12113. this.dPadDown = this.browserGamepad.buttons[13].value;
  12114. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12115. this.dPadRight = this.browserGamepad.buttons[15].value;
  12116. };
  12117. return Xbox360Pad;
  12118. })(Gamepad);
  12119. BABYLON.Xbox360Pad = Xbox360Pad;
  12120. })(BABYLON || (BABYLON = {}));
  12121. var BABYLON;
  12122. (function (BABYLON) {
  12123. // We're mainly based on the logic defined into the FreeCamera code
  12124. var GamepadCamera = (function (_super) {
  12125. __extends(GamepadCamera, _super);
  12126. function GamepadCamera(name, position, scene) {
  12127. var _this = this;
  12128. _super.call(this, name, position, scene);
  12129. this.angularSensibility = 200;
  12130. this.moveSensibility = 75;
  12131. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12132. }
  12133. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12134. // Only the first gamepad can control the camera
  12135. if (gamepad.index === 0) {
  12136. this._gamepad = gamepad;
  12137. }
  12138. };
  12139. GamepadCamera.prototype._checkInputs = function () {
  12140. if (this._gamepad) {
  12141. var LSValues = this._gamepad.leftStick;
  12142. var normalizedLX = LSValues.x / this.moveSensibility;
  12143. var normalizedLY = LSValues.y / this.moveSensibility;
  12144. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12145. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12146. var RSValues = this._gamepad.rightStick;
  12147. var normalizedRX = RSValues.x / this.angularSensibility;
  12148. var normalizedRY = RSValues.y / this.angularSensibility;
  12149. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12150. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12151. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12152. var speed = this._computeLocalCameraSpeed() * 50.0;
  12153. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12154. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12155. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12156. }
  12157. _super.prototype._checkInputs.call(this);
  12158. };
  12159. GamepadCamera.prototype.dispose = function () {
  12160. this._gamepads.dispose();
  12161. _super.prototype.dispose.call(this);
  12162. };
  12163. return GamepadCamera;
  12164. })(BABYLON.FreeCamera);
  12165. BABYLON.GamepadCamera = GamepadCamera;
  12166. })(BABYLON || (BABYLON = {}));
  12167. var BABYLON;
  12168. (function (BABYLON) {
  12169. var RenderingManager = (function () {
  12170. function RenderingManager(scene) {
  12171. this._renderingGroups = new Array();
  12172. this._scene = scene;
  12173. }
  12174. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12175. if (this._scene._activeParticleSystems.length === 0) {
  12176. return;
  12177. }
  12178. // Particles
  12179. var beforeParticlesDate = BABYLON.Tools.Now;
  12180. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12181. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12182. if (particleSystem.renderingGroupId !== index) {
  12183. continue;
  12184. }
  12185. this._clearDepthBuffer();
  12186. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12187. this._scene._activeParticles += particleSystem.render();
  12188. }
  12189. }
  12190. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12191. };
  12192. RenderingManager.prototype._renderSprites = function (index) {
  12193. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12194. return;
  12195. }
  12196. // Sprites
  12197. var beforeSpritessDate = BABYLON.Tools.Now;
  12198. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12199. var spriteManager = this._scene.spriteManagers[id];
  12200. if (spriteManager.renderingGroupId === index) {
  12201. this._clearDepthBuffer();
  12202. spriteManager.render();
  12203. }
  12204. }
  12205. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12206. };
  12207. RenderingManager.prototype._clearDepthBuffer = function () {
  12208. if (this._depthBufferAlreadyCleaned) {
  12209. return;
  12210. }
  12211. this._scene.getEngine().clear(0, false, true);
  12212. this._depthBufferAlreadyCleaned = true;
  12213. };
  12214. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12215. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12216. this._depthBufferAlreadyCleaned = false;
  12217. var renderingGroup = this._renderingGroups[index];
  12218. var needToStepBack = false;
  12219. if (renderingGroup) {
  12220. this._clearDepthBuffer();
  12221. if (!renderingGroup.render(customRenderFunction)) {
  12222. this._renderingGroups.splice(index, 1);
  12223. needToStepBack = true;
  12224. }
  12225. }
  12226. if (renderSprites) {
  12227. this._renderSprites(index);
  12228. }
  12229. if (renderParticles) {
  12230. this._renderParticles(index, activeMeshes);
  12231. }
  12232. if (needToStepBack) {
  12233. index--;
  12234. }
  12235. }
  12236. };
  12237. RenderingManager.prototype.reset = function () {
  12238. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12239. if (renderingGroup) {
  12240. renderingGroup.prepare();
  12241. }
  12242. });
  12243. };
  12244. RenderingManager.prototype.dispatch = function (subMesh) {
  12245. var mesh = subMesh.getMesh();
  12246. var renderingGroupId = mesh.renderingGroupId || 0;
  12247. if (!this._renderingGroups[renderingGroupId]) {
  12248. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12249. }
  12250. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12251. };
  12252. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12253. return RenderingManager;
  12254. })();
  12255. BABYLON.RenderingManager = RenderingManager;
  12256. })(BABYLON || (BABYLON = {}));
  12257. var BABYLON;
  12258. (function (BABYLON) {
  12259. var RenderingGroup = (function () {
  12260. function RenderingGroup(index, scene) {
  12261. this.index = index;
  12262. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12263. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12264. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12265. this._scene = scene;
  12266. }
  12267. RenderingGroup.prototype.render = function (customRenderFunction) {
  12268. if (customRenderFunction) {
  12269. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12270. return true;
  12271. }
  12272. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12273. return false;
  12274. }
  12275. var engine = this._scene.getEngine();
  12276. // Opaque
  12277. var subIndex;
  12278. var submesh;
  12279. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12280. submesh = this._opaqueSubMeshes.data[subIndex];
  12281. submesh.render(false);
  12282. }
  12283. // Alpha test
  12284. engine.setAlphaTesting(true);
  12285. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12286. submesh = this._alphaTestSubMeshes.data[subIndex];
  12287. submesh.render(false);
  12288. }
  12289. engine.setAlphaTesting(false);
  12290. // Transparent
  12291. if (this._transparentSubMeshes.length) {
  12292. // Sorting
  12293. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12294. submesh = this._transparentSubMeshes.data[subIndex];
  12295. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12296. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12297. }
  12298. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12299. sortedArray.sort(function (a, b) {
  12300. // Alpha index first
  12301. if (a._alphaIndex > b._alphaIndex) {
  12302. return 1;
  12303. }
  12304. if (a._alphaIndex < b._alphaIndex) {
  12305. return -1;
  12306. }
  12307. // Then distance to camera
  12308. if (a._distanceToCamera < b._distanceToCamera) {
  12309. return 1;
  12310. }
  12311. if (a._distanceToCamera > b._distanceToCamera) {
  12312. return -1;
  12313. }
  12314. return 0;
  12315. });
  12316. // Rendering
  12317. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12318. submesh = sortedArray[subIndex];
  12319. submesh.render(true);
  12320. }
  12321. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12322. }
  12323. return true;
  12324. };
  12325. RenderingGroup.prototype.prepare = function () {
  12326. this._opaqueSubMeshes.reset();
  12327. this._transparentSubMeshes.reset();
  12328. this._alphaTestSubMeshes.reset();
  12329. };
  12330. RenderingGroup.prototype.dispatch = function (subMesh) {
  12331. var material = subMesh.getMaterial();
  12332. var mesh = subMesh.getMesh();
  12333. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12334. this._transparentSubMeshes.push(subMesh);
  12335. }
  12336. else if (material.needAlphaTesting()) {
  12337. this._alphaTestSubMeshes.push(subMesh);
  12338. }
  12339. else {
  12340. this._opaqueSubMeshes.push(subMesh); // Opaque
  12341. }
  12342. };
  12343. return RenderingGroup;
  12344. })();
  12345. BABYLON.RenderingGroup = RenderingGroup;
  12346. })(BABYLON || (BABYLON = {}));
  12347. var BABYLON;
  12348. (function (BABYLON) {
  12349. /**
  12350. * Represents a scene to be rendered by the engine.
  12351. * @see http://doc.babylonjs.com/page.php?p=21911
  12352. */
  12353. var Scene = (function () {
  12354. /**
  12355. * @constructor
  12356. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12357. */
  12358. function Scene(engine) {
  12359. // Members
  12360. this.autoClear = true;
  12361. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12362. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12363. this.forceWireframe = false;
  12364. this.forcePointsCloud = false;
  12365. this.forceShowBoundingBoxes = false;
  12366. this.animationsEnabled = true;
  12367. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12368. // Fog
  12369. /**
  12370. * is fog enabled on this scene.
  12371. * @type {boolean}
  12372. */
  12373. this.fogEnabled = true;
  12374. this.fogMode = Scene.FOGMODE_NONE;
  12375. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12376. this.fogDensity = 0.1;
  12377. this.fogStart = 0;
  12378. this.fogEnd = 1000.0;
  12379. // Lights
  12380. /**
  12381. * is shadow enabled on this scene.
  12382. * @type {boolean}
  12383. */
  12384. this.shadowsEnabled = true;
  12385. /**
  12386. * is light enabled on this scene.
  12387. * @type {boolean}
  12388. */
  12389. this.lightsEnabled = true;
  12390. /**
  12391. * All of the lights added to this scene.
  12392. * @see BABYLON.Light
  12393. * @type {BABYLON.Light[]}
  12394. */
  12395. this.lights = new Array();
  12396. // Cameras
  12397. /**
  12398. * All of the cameras added to this scene.
  12399. * @see BABYLON.Camera
  12400. * @type {BABYLON.Camera[]}
  12401. */
  12402. this.cameras = new Array();
  12403. this.activeCameras = new Array();
  12404. // Meshes
  12405. /**
  12406. * All of the (abstract) meshes added to this scene.
  12407. * @see BABYLON.AbstractMesh
  12408. * @type {BABYLON.AbstractMesh[]}
  12409. */
  12410. this.meshes = new Array();
  12411. // Geometries
  12412. this._geometries = new Array();
  12413. this.materials = new Array();
  12414. this.multiMaterials = new Array();
  12415. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12416. // Textures
  12417. this.texturesEnabled = true;
  12418. this.textures = new Array();
  12419. // Particles
  12420. this.particlesEnabled = true;
  12421. this.particleSystems = new Array();
  12422. // Sprites
  12423. this.spritesEnabled = true;
  12424. this.spriteManagers = new Array();
  12425. // Layers
  12426. this.layers = new Array();
  12427. // Skeletons
  12428. this.skeletonsEnabled = true;
  12429. this.skeletons = new Array();
  12430. // Lens flares
  12431. this.lensFlaresEnabled = true;
  12432. this.lensFlareSystems = new Array();
  12433. // Collisions
  12434. this.collisionsEnabled = true;
  12435. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12436. // Postprocesses
  12437. this.postProcessesEnabled = true;
  12438. // Customs render targets
  12439. this.renderTargetsEnabled = true;
  12440. this.dumpNextRenderTargets = false;
  12441. this.customRenderTargets = new Array();
  12442. // Imported meshes
  12443. this.importedMeshesFiles = new Array();
  12444. this._actionManagers = new Array();
  12445. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12446. // Procedural textures
  12447. this.proceduralTexturesEnabled = true;
  12448. this._proceduralTextures = new Array();
  12449. this.soundTracks = new Array();
  12450. this._audioEnabled = true;
  12451. this._headphone = false;
  12452. this._totalVertices = 0;
  12453. this._activeIndices = 0;
  12454. this._activeParticles = 0;
  12455. this._lastFrameDuration = 0;
  12456. this._evaluateActiveMeshesDuration = 0;
  12457. this._renderTargetsDuration = 0;
  12458. this._particlesDuration = 0;
  12459. this._renderDuration = 0;
  12460. this._spritesDuration = 0;
  12461. this._animationRatio = 0;
  12462. this._renderId = 0;
  12463. this._executeWhenReadyTimeoutId = -1;
  12464. this._toBeDisposed = new BABYLON.SmartArray(256);
  12465. this._onReadyCallbacks = new Array();
  12466. this._pendingData = []; //ANY
  12467. this._onBeforeRenderCallbacks = new Array();
  12468. this._onAfterRenderCallbacks = new Array();
  12469. this._activeMeshes = new BABYLON.SmartArray(256);
  12470. this._processedMaterials = new BABYLON.SmartArray(256);
  12471. this._renderTargets = new BABYLON.SmartArray(256);
  12472. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12473. this._activeSkeletons = new BABYLON.SmartArray(32);
  12474. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12475. this._activeBones = 0;
  12476. this._activeAnimatables = new Array();
  12477. this._transformMatrix = BABYLON.Matrix.Zero();
  12478. this._edgesRenderers = new BABYLON.SmartArray(16);
  12479. this._uniqueIdCounter = 0;
  12480. this._engine = engine;
  12481. engine.scenes.push(this);
  12482. this._renderingManager = new BABYLON.RenderingManager(this);
  12483. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12484. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12485. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12486. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12487. this.attachControl();
  12488. this._debugLayer = new BABYLON.DebugLayer(this);
  12489. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12490. //simplification queue
  12491. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12492. //collision coordinator initialization. For now legacy per default.
  12493. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12494. }
  12495. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12496. get: function () {
  12497. return Scene._FOGMODE_NONE;
  12498. },
  12499. enumerable: true,
  12500. configurable: true
  12501. });
  12502. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12503. get: function () {
  12504. return Scene._FOGMODE_EXP;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12510. get: function () {
  12511. return Scene._FOGMODE_EXP2;
  12512. },
  12513. enumerable: true,
  12514. configurable: true
  12515. });
  12516. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12517. get: function () {
  12518. return Scene._FOGMODE_LINEAR;
  12519. },
  12520. enumerable: true,
  12521. configurable: true
  12522. });
  12523. Object.defineProperty(Scene.prototype, "debugLayer", {
  12524. // Properties
  12525. get: function () {
  12526. return this._debugLayer;
  12527. },
  12528. enumerable: true,
  12529. configurable: true
  12530. });
  12531. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12532. get: function () {
  12533. return this._workerCollisions;
  12534. },
  12535. set: function (enabled) {
  12536. enabled = (enabled && !!Worker);
  12537. this._workerCollisions = enabled;
  12538. if (this.collisionCoordinator) {
  12539. this.collisionCoordinator.destroy();
  12540. }
  12541. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12542. this.collisionCoordinator.init(this);
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12548. get: function () {
  12549. return this._selectionOctree;
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12555. /**
  12556. * The mesh that is currently under the pointer.
  12557. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12558. */
  12559. get: function () {
  12560. return this._meshUnderPointer;
  12561. },
  12562. enumerable: true,
  12563. configurable: true
  12564. });
  12565. Object.defineProperty(Scene.prototype, "pointerX", {
  12566. /**
  12567. * Current on-screen X position of the pointer
  12568. * @return {number} X position of the pointer
  12569. */
  12570. get: function () {
  12571. return this._pointerX;
  12572. },
  12573. enumerable: true,
  12574. configurable: true
  12575. });
  12576. Object.defineProperty(Scene.prototype, "pointerY", {
  12577. /**
  12578. * Current on-screen Y position of the pointer
  12579. * @return {number} Y position of the pointer
  12580. */
  12581. get: function () {
  12582. return this._pointerY;
  12583. },
  12584. enumerable: true,
  12585. configurable: true
  12586. });
  12587. Scene.prototype.getCachedMaterial = function () {
  12588. return this._cachedMaterial;
  12589. };
  12590. Scene.prototype.getBoundingBoxRenderer = function () {
  12591. return this._boundingBoxRenderer;
  12592. };
  12593. Scene.prototype.getOutlineRenderer = function () {
  12594. return this._outlineRenderer;
  12595. };
  12596. Scene.prototype.getEngine = function () {
  12597. return this._engine;
  12598. };
  12599. Scene.prototype.getTotalVertices = function () {
  12600. return this._totalVertices;
  12601. };
  12602. Scene.prototype.getActiveIndices = function () {
  12603. return this._activeIndices;
  12604. };
  12605. Scene.prototype.getActiveParticles = function () {
  12606. return this._activeParticles;
  12607. };
  12608. Scene.prototype.getActiveBones = function () {
  12609. return this._activeBones;
  12610. };
  12611. // Stats
  12612. Scene.prototype.getLastFrameDuration = function () {
  12613. return this._lastFrameDuration;
  12614. };
  12615. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12616. return this._evaluateActiveMeshesDuration;
  12617. };
  12618. Scene.prototype.getActiveMeshes = function () {
  12619. return this._activeMeshes;
  12620. };
  12621. Scene.prototype.getRenderTargetsDuration = function () {
  12622. return this._renderTargetsDuration;
  12623. };
  12624. Scene.prototype.getRenderDuration = function () {
  12625. return this._renderDuration;
  12626. };
  12627. Scene.prototype.getParticlesDuration = function () {
  12628. return this._particlesDuration;
  12629. };
  12630. Scene.prototype.getSpritesDuration = function () {
  12631. return this._spritesDuration;
  12632. };
  12633. Scene.prototype.getAnimationRatio = function () {
  12634. return this._animationRatio;
  12635. };
  12636. Scene.prototype.getRenderId = function () {
  12637. return this._renderId;
  12638. };
  12639. Scene.prototype.incrementRenderId = function () {
  12640. this._renderId++;
  12641. };
  12642. Scene.prototype._updatePointerPosition = function (evt) {
  12643. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12644. this._pointerX = evt.clientX - canvasRect.left;
  12645. this._pointerY = evt.clientY - canvasRect.top;
  12646. if (this.cameraToUseForPointers) {
  12647. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12648. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12649. }
  12650. };
  12651. // Pointers handling
  12652. Scene.prototype.attachControl = function () {
  12653. var _this = this;
  12654. this._onPointerMove = function (evt) {
  12655. var canvas = _this._engine.getRenderingCanvas();
  12656. _this._updatePointerPosition(evt);
  12657. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12658. if (pickResult.hit) {
  12659. _this._meshUnderPointer = pickResult.pickedMesh;
  12660. _this.setPointerOverMesh(pickResult.pickedMesh);
  12661. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12662. canvas.style.cursor = "pointer";
  12663. }
  12664. else {
  12665. canvas.style.cursor = "";
  12666. }
  12667. }
  12668. else {
  12669. _this.setPointerOverMesh(null);
  12670. canvas.style.cursor = "";
  12671. _this._meshUnderPointer = null;
  12672. }
  12673. };
  12674. this._onPointerDown = function (evt) {
  12675. var predicate = null;
  12676. if (!_this.onPointerDown) {
  12677. predicate = function (mesh) {
  12678. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12679. };
  12680. }
  12681. _this._updatePointerPosition(evt);
  12682. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12683. if (pickResult.hit) {
  12684. if (pickResult.pickedMesh.actionManager) {
  12685. switch (evt.button) {
  12686. case 0:
  12687. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12688. break;
  12689. case 1:
  12690. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12691. break;
  12692. case 2:
  12693. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12694. break;
  12695. }
  12696. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12697. }
  12698. }
  12699. if (_this.onPointerDown) {
  12700. _this.onPointerDown(evt, pickResult);
  12701. }
  12702. };
  12703. this._onPointerUp = function (evt) {
  12704. var predicate = null;
  12705. if (!_this.onPointerUp) {
  12706. predicate = function (mesh) {
  12707. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12708. };
  12709. }
  12710. _this._updatePointerPosition(evt);
  12711. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12712. if (pickResult.hit) {
  12713. if (pickResult.pickedMesh.actionManager) {
  12714. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12715. }
  12716. }
  12717. if (_this.onPointerUp) {
  12718. _this.onPointerUp(evt, pickResult);
  12719. }
  12720. };
  12721. this._onKeyDown = function (evt) {
  12722. if (_this.actionManager) {
  12723. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12724. }
  12725. };
  12726. this._onKeyUp = function (evt) {
  12727. if (_this.actionManager) {
  12728. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12729. }
  12730. };
  12731. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12732. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12733. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12734. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12735. // Wheel
  12736. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12737. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12738. BABYLON.Tools.RegisterTopRootEvents([
  12739. { name: "keydown", handler: this._onKeyDown },
  12740. { name: "keyup", handler: this._onKeyUp }
  12741. ]);
  12742. };
  12743. Scene.prototype.detachControl = function () {
  12744. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12745. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12746. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12747. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12748. // Wheel
  12749. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12750. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12751. BABYLON.Tools.UnregisterTopRootEvents([
  12752. { name: "keydown", handler: this._onKeyDown },
  12753. { name: "keyup", handler: this._onKeyUp }
  12754. ]);
  12755. };
  12756. // Ready
  12757. Scene.prototype.isReady = function () {
  12758. if (this._pendingData.length > 0) {
  12759. return false;
  12760. }
  12761. var index;
  12762. for (index = 0; index < this._geometries.length; index++) {
  12763. var geometry = this._geometries[index];
  12764. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12765. return false;
  12766. }
  12767. }
  12768. for (index = 0; index < this.meshes.length; index++) {
  12769. var mesh = this.meshes[index];
  12770. if (!mesh.isReady()) {
  12771. return false;
  12772. }
  12773. var mat = mesh.material;
  12774. if (mat) {
  12775. if (!mat.isReady(mesh)) {
  12776. return false;
  12777. }
  12778. }
  12779. }
  12780. return true;
  12781. };
  12782. Scene.prototype.resetCachedMaterial = function () {
  12783. this._cachedMaterial = null;
  12784. };
  12785. Scene.prototype.registerBeforeRender = function (func) {
  12786. this._onBeforeRenderCallbacks.push(func);
  12787. };
  12788. Scene.prototype.unregisterBeforeRender = function (func) {
  12789. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12790. if (index > -1) {
  12791. this._onBeforeRenderCallbacks.splice(index, 1);
  12792. }
  12793. };
  12794. Scene.prototype.registerAfterRender = function (func) {
  12795. this._onAfterRenderCallbacks.push(func);
  12796. };
  12797. Scene.prototype.unregisterAfterRender = function (func) {
  12798. var index = this._onAfterRenderCallbacks.indexOf(func);
  12799. if (index > -1) {
  12800. this._onAfterRenderCallbacks.splice(index, 1);
  12801. }
  12802. };
  12803. Scene.prototype._addPendingData = function (data) {
  12804. this._pendingData.push(data);
  12805. };
  12806. Scene.prototype._removePendingData = function (data) {
  12807. var index = this._pendingData.indexOf(data);
  12808. if (index !== -1) {
  12809. this._pendingData.splice(index, 1);
  12810. }
  12811. };
  12812. Scene.prototype.getWaitingItemsCount = function () {
  12813. return this._pendingData.length;
  12814. };
  12815. /**
  12816. * Registers a function to be executed when the scene is ready.
  12817. * @param {Function} func - the function to be executed.
  12818. */
  12819. Scene.prototype.executeWhenReady = function (func) {
  12820. var _this = this;
  12821. this._onReadyCallbacks.push(func);
  12822. if (this._executeWhenReadyTimeoutId !== -1) {
  12823. return;
  12824. }
  12825. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12826. _this._checkIsReady();
  12827. }, 150);
  12828. };
  12829. Scene.prototype._checkIsReady = function () {
  12830. var _this = this;
  12831. if (this.isReady()) {
  12832. this._onReadyCallbacks.forEach(function (func) {
  12833. func();
  12834. });
  12835. this._onReadyCallbacks = [];
  12836. this._executeWhenReadyTimeoutId = -1;
  12837. return;
  12838. }
  12839. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12840. _this._checkIsReady();
  12841. }, 150);
  12842. };
  12843. // Animations
  12844. /**
  12845. * Will start the animation sequence of a given target
  12846. * @param target - the target
  12847. * @param {number} from - from which frame should animation start
  12848. * @param {number} to - till which frame should animation run.
  12849. * @param {boolean} [loop] - should the animation loop
  12850. * @param {number} [speedRatio] - the speed in which to run the animation
  12851. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12852. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12853. * @return {BABYLON.Animatable} the animatable object created for this animation
  12854. * @see BABYLON.Animatable
  12855. * @see http://doc.babylonjs.com/page.php?p=22081
  12856. */
  12857. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12858. if (speedRatio === undefined) {
  12859. speedRatio = 1.0;
  12860. }
  12861. this.stopAnimation(target);
  12862. if (!animatable) {
  12863. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12864. }
  12865. // Local animations
  12866. if (target.animations) {
  12867. animatable.appendAnimations(target, target.animations);
  12868. }
  12869. // Children animations
  12870. if (target.getAnimatables) {
  12871. var animatables = target.getAnimatables();
  12872. for (var index = 0; index < animatables.length; index++) {
  12873. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12874. }
  12875. }
  12876. return animatable;
  12877. };
  12878. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12879. if (speedRatio === undefined) {
  12880. speedRatio = 1.0;
  12881. }
  12882. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12883. return animatable;
  12884. };
  12885. Scene.prototype.getAnimatableByTarget = function (target) {
  12886. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12887. if (this._activeAnimatables[index].target === target) {
  12888. return this._activeAnimatables[index];
  12889. }
  12890. }
  12891. return null;
  12892. };
  12893. /**
  12894. * Will stop the animation of the given target
  12895. * @param target - the target
  12896. * @see beginAnimation
  12897. */
  12898. Scene.prototype.stopAnimation = function (target) {
  12899. var animatable = this.getAnimatableByTarget(target);
  12900. if (animatable) {
  12901. animatable.stop();
  12902. }
  12903. };
  12904. Scene.prototype._animate = function () {
  12905. if (!this.animationsEnabled) {
  12906. return;
  12907. }
  12908. if (!this._animationStartDate) {
  12909. this._animationStartDate = BABYLON.Tools.Now;
  12910. }
  12911. // Getting time
  12912. var now = BABYLON.Tools.Now;
  12913. var delay = now - this._animationStartDate;
  12914. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12915. this._activeAnimatables[index]._animate(delay);
  12916. }
  12917. };
  12918. // Matrix
  12919. Scene.prototype.getViewMatrix = function () {
  12920. return this._viewMatrix;
  12921. };
  12922. Scene.prototype.getProjectionMatrix = function () {
  12923. return this._projectionMatrix;
  12924. };
  12925. Scene.prototype.getTransformMatrix = function () {
  12926. return this._transformMatrix;
  12927. };
  12928. Scene.prototype.setTransformMatrix = function (view, projection) {
  12929. this._viewMatrix = view;
  12930. this._projectionMatrix = projection;
  12931. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12932. };
  12933. // Methods
  12934. Scene.prototype.addMesh = function (newMesh) {
  12935. newMesh.uniqueId = this._uniqueIdCounter++;
  12936. var position = this.meshes.push(newMesh);
  12937. //notify the collision coordinator
  12938. this.collisionCoordinator.onMeshAdded(newMesh);
  12939. if (this.onNewMeshAdded) {
  12940. this.onNewMeshAdded(newMesh, position, this);
  12941. }
  12942. };
  12943. Scene.prototype.removeMesh = function (toRemove) {
  12944. var index = this.meshes.indexOf(toRemove);
  12945. if (index !== -1) {
  12946. // Remove from the scene if mesh found
  12947. this.meshes.splice(index, 1);
  12948. }
  12949. //notify the collision coordinator
  12950. this.collisionCoordinator.onMeshRemoved(toRemove);
  12951. if (this.onMeshRemoved) {
  12952. this.onMeshRemoved(toRemove);
  12953. }
  12954. return index;
  12955. };
  12956. Scene.prototype.removeLight = function (toRemove) {
  12957. var index = this.lights.indexOf(toRemove);
  12958. if (index !== -1) {
  12959. // Remove from the scene if mesh found
  12960. this.lights.splice(index, 1);
  12961. }
  12962. if (this.onLightRemoved) {
  12963. this.onLightRemoved(toRemove);
  12964. }
  12965. return index;
  12966. };
  12967. Scene.prototype.removeCamera = function (toRemove) {
  12968. var index = this.cameras.indexOf(toRemove);
  12969. if (index !== -1) {
  12970. // Remove from the scene if mesh found
  12971. this.cameras.splice(index, 1);
  12972. }
  12973. // Remove from activeCameras
  12974. var index2 = this.activeCameras.indexOf(toRemove);
  12975. if (index2 !== -1) {
  12976. // Remove from the scene if mesh found
  12977. this.activeCameras.splice(index2, 1);
  12978. }
  12979. // Reset the activeCamera
  12980. if (this.activeCamera === toRemove) {
  12981. if (this.cameras.length > 0) {
  12982. this.activeCamera = this.cameras[0];
  12983. }
  12984. else {
  12985. this.activeCamera = null;
  12986. }
  12987. }
  12988. if (this.onCameraRemoved) {
  12989. this.onCameraRemoved(toRemove);
  12990. }
  12991. return index;
  12992. };
  12993. Scene.prototype.addLight = function (newLight) {
  12994. newLight.uniqueId = this._uniqueIdCounter++;
  12995. var position = this.lights.push(newLight);
  12996. if (this.onNewLightAdded) {
  12997. this.onNewLightAdded(newLight, position, this);
  12998. }
  12999. };
  13000. Scene.prototype.addCamera = function (newCamera) {
  13001. newCamera.uniqueId = this._uniqueIdCounter++;
  13002. var position = this.cameras.push(newCamera);
  13003. if (this.onNewCameraAdded) {
  13004. this.onNewCameraAdded(newCamera, position, this);
  13005. }
  13006. };
  13007. /**
  13008. * sets the active camera of the scene using its ID
  13009. * @param {string} id - the camera's ID
  13010. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13011. * @see activeCamera
  13012. */
  13013. Scene.prototype.setActiveCameraByID = function (id) {
  13014. var camera = this.getCameraByID(id);
  13015. if (camera) {
  13016. this.activeCamera = camera;
  13017. return camera;
  13018. }
  13019. return null;
  13020. };
  13021. /**
  13022. * sets the active camera of the scene using its name
  13023. * @param {string} name - the camera's name
  13024. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13025. * @see activeCamera
  13026. */
  13027. Scene.prototype.setActiveCameraByName = function (name) {
  13028. var camera = this.getCameraByName(name);
  13029. if (camera) {
  13030. this.activeCamera = camera;
  13031. return camera;
  13032. }
  13033. return null;
  13034. };
  13035. /**
  13036. * get a material using its id
  13037. * @param {string} the material's ID
  13038. * @return {BABYLON.Material|null} the material or null if none found.
  13039. */
  13040. Scene.prototype.getMaterialByID = function (id) {
  13041. for (var index = 0; index < this.materials.length; index++) {
  13042. if (this.materials[index].id === id) {
  13043. return this.materials[index];
  13044. }
  13045. }
  13046. return null;
  13047. };
  13048. /**
  13049. * get a material using its name
  13050. * @param {string} the material's name
  13051. * @return {BABYLON.Material|null} the material or null if none found.
  13052. */
  13053. Scene.prototype.getMaterialByName = function (name) {
  13054. for (var index = 0; index < this.materials.length; index++) {
  13055. if (this.materials[index].name === name) {
  13056. return this.materials[index];
  13057. }
  13058. }
  13059. return null;
  13060. };
  13061. Scene.prototype.getLensFlareSystemByName = function (name) {
  13062. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13063. if (this.lensFlareSystems[index].name === name) {
  13064. return this.lensFlareSystems[index];
  13065. }
  13066. }
  13067. return null;
  13068. };
  13069. Scene.prototype.getCameraByID = function (id) {
  13070. for (var index = 0; index < this.cameras.length; index++) {
  13071. if (this.cameras[index].id === id) {
  13072. return this.cameras[index];
  13073. }
  13074. }
  13075. return null;
  13076. };
  13077. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13078. for (var index = 0; index < this.cameras.length; index++) {
  13079. if (this.cameras[index].uniqueId === uniqueId) {
  13080. return this.cameras[index];
  13081. }
  13082. }
  13083. return null;
  13084. };
  13085. /**
  13086. * get a camera using its name
  13087. * @param {string} the camera's name
  13088. * @return {BABYLON.Camera|null} the camera or null if none found.
  13089. */
  13090. Scene.prototype.getCameraByName = function (name) {
  13091. for (var index = 0; index < this.cameras.length; index++) {
  13092. if (this.cameras[index].name === name) {
  13093. return this.cameras[index];
  13094. }
  13095. }
  13096. return null;
  13097. };
  13098. /**
  13099. * get a light node using its name
  13100. * @param {string} the light's name
  13101. * @return {BABYLON.Light|null} the light or null if none found.
  13102. */
  13103. Scene.prototype.getLightByName = function (name) {
  13104. for (var index = 0; index < this.lights.length; index++) {
  13105. if (this.lights[index].name === name) {
  13106. return this.lights[index];
  13107. }
  13108. }
  13109. return null;
  13110. };
  13111. /**
  13112. * get a light node using its ID
  13113. * @param {string} the light's id
  13114. * @return {BABYLON.Light|null} the light or null if none found.
  13115. */
  13116. Scene.prototype.getLightByID = function (id) {
  13117. for (var index = 0; index < this.lights.length; index++) {
  13118. if (this.lights[index].id === id) {
  13119. return this.lights[index];
  13120. }
  13121. }
  13122. return null;
  13123. };
  13124. /**
  13125. * get a light node using its scene-generated unique ID
  13126. * @param {number} the light's unique id
  13127. * @return {BABYLON.Light|null} the light or null if none found.
  13128. */
  13129. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13130. for (var index = 0; index < this.lights.length; index++) {
  13131. if (this.lights[index].uniqueId === uniqueId) {
  13132. return this.lights[index];
  13133. }
  13134. }
  13135. return null;
  13136. };
  13137. /**
  13138. * get a geometry using its ID
  13139. * @param {string} the geometry's id
  13140. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13141. */
  13142. Scene.prototype.getGeometryByID = function (id) {
  13143. for (var index = 0; index < this._geometries.length; index++) {
  13144. if (this._geometries[index].id === id) {
  13145. return this._geometries[index];
  13146. }
  13147. }
  13148. return null;
  13149. };
  13150. /**
  13151. * add a new geometry to this scene.
  13152. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13153. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13154. * @return {boolean} was the geometry added or not
  13155. */
  13156. Scene.prototype.pushGeometry = function (geometry, force) {
  13157. if (!force && this.getGeometryByID(geometry.id)) {
  13158. return false;
  13159. }
  13160. this._geometries.push(geometry);
  13161. //notify the collision coordinator
  13162. this.collisionCoordinator.onGeometryAdded(geometry);
  13163. if (this.onGeometryAdded) {
  13164. this.onGeometryAdded(geometry);
  13165. }
  13166. return true;
  13167. };
  13168. /**
  13169. * Removes an existing geometry
  13170. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13171. * @return {boolean} was the geometry removed or not
  13172. */
  13173. Scene.prototype.removeGeometry = function (geometry) {
  13174. var index = this._geometries.indexOf(geometry);
  13175. if (index > -1) {
  13176. this._geometries.splice(index, 1);
  13177. //notify the collision coordinator
  13178. this.collisionCoordinator.onGeometryDeleted(geometry);
  13179. if (this.onGeometryRemoved) {
  13180. this.onGeometryRemoved(geometry);
  13181. }
  13182. return true;
  13183. }
  13184. return false;
  13185. };
  13186. Scene.prototype.getGeometries = function () {
  13187. return this._geometries;
  13188. };
  13189. /**
  13190. * Get the first added mesh found of a given ID
  13191. * @param {string} id - the id to search for
  13192. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13193. */
  13194. Scene.prototype.getMeshByID = function (id) {
  13195. for (var index = 0; index < this.meshes.length; index++) {
  13196. if (this.meshes[index].id === id) {
  13197. return this.meshes[index];
  13198. }
  13199. }
  13200. return null;
  13201. };
  13202. /**
  13203. * Get a mesh with its auto-generated unique id
  13204. * @param {number} uniqueId - the unique id to search for
  13205. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13206. */
  13207. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13208. for (var index = 0; index < this.meshes.length; index++) {
  13209. if (this.meshes[index].uniqueId === uniqueId) {
  13210. return this.meshes[index];
  13211. }
  13212. }
  13213. return null;
  13214. };
  13215. /**
  13216. * Get a the last added mesh found of a given ID
  13217. * @param {string} id - the id to search for
  13218. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13219. */
  13220. Scene.prototype.getLastMeshByID = function (id) {
  13221. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13222. if (this.meshes[index].id === id) {
  13223. return this.meshes[index];
  13224. }
  13225. }
  13226. return null;
  13227. };
  13228. /**
  13229. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13230. * @param {string} id - the id to search for
  13231. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13232. */
  13233. Scene.prototype.getLastEntryByID = function (id) {
  13234. var index;
  13235. for (index = this.meshes.length - 1; index >= 0; index--) {
  13236. if (this.meshes[index].id === id) {
  13237. return this.meshes[index];
  13238. }
  13239. }
  13240. for (index = this.cameras.length - 1; index >= 0; index--) {
  13241. if (this.cameras[index].id === id) {
  13242. return this.cameras[index];
  13243. }
  13244. }
  13245. for (index = this.lights.length - 1; index >= 0; index--) {
  13246. if (this.lights[index].id === id) {
  13247. return this.lights[index];
  13248. }
  13249. }
  13250. return null;
  13251. };
  13252. Scene.prototype.getNodeByID = function (id) {
  13253. var mesh = this.getMeshByID(id);
  13254. if (mesh) {
  13255. return mesh;
  13256. }
  13257. var light = this.getLightByID(id);
  13258. if (light) {
  13259. return light;
  13260. }
  13261. return this.getCameraByID(id);
  13262. };
  13263. Scene.prototype.getNodeByName = function (name) {
  13264. var mesh = this.getMeshByName(name);
  13265. if (mesh) {
  13266. return mesh;
  13267. }
  13268. var light = this.getLightByName(name);
  13269. if (light) {
  13270. return light;
  13271. }
  13272. return this.getCameraByName(name);
  13273. };
  13274. Scene.prototype.getMeshByName = function (name) {
  13275. for (var index = 0; index < this.meshes.length; index++) {
  13276. if (this.meshes[index].name === name) {
  13277. return this.meshes[index];
  13278. }
  13279. }
  13280. return null;
  13281. };
  13282. Scene.prototype.getSoundByName = function (name) {
  13283. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13284. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13285. return this.mainSoundTrack.soundCollection[index];
  13286. }
  13287. }
  13288. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13289. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13290. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13291. return this.soundTracks[sdIndex].soundCollection[index];
  13292. }
  13293. }
  13294. }
  13295. return null;
  13296. };
  13297. Scene.prototype.getLastSkeletonByID = function (id) {
  13298. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13299. if (this.skeletons[index].id === id) {
  13300. return this.skeletons[index];
  13301. }
  13302. }
  13303. return null;
  13304. };
  13305. Scene.prototype.getSkeletonById = function (id) {
  13306. for (var index = 0; index < this.skeletons.length; index++) {
  13307. if (this.skeletons[index].id === id) {
  13308. return this.skeletons[index];
  13309. }
  13310. }
  13311. return null;
  13312. };
  13313. Scene.prototype.getSkeletonByName = function (name) {
  13314. for (var index = 0; index < this.skeletons.length; index++) {
  13315. if (this.skeletons[index].name === name) {
  13316. return this.skeletons[index];
  13317. }
  13318. }
  13319. return null;
  13320. };
  13321. Scene.prototype.isActiveMesh = function (mesh) {
  13322. return (this._activeMeshes.indexOf(mesh) !== -1);
  13323. };
  13324. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13325. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13326. var material = subMesh.getMaterial();
  13327. if (mesh.showSubMeshesBoundingBox) {
  13328. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13329. }
  13330. if (material) {
  13331. // Render targets
  13332. if (material.getRenderTargetTextures) {
  13333. if (this._processedMaterials.indexOf(material) === -1) {
  13334. this._processedMaterials.push(material);
  13335. this._renderTargets.concat(material.getRenderTargetTextures());
  13336. }
  13337. }
  13338. // Dispatch
  13339. this._activeIndices += subMesh.indexCount;
  13340. this._renderingManager.dispatch(subMesh);
  13341. }
  13342. }
  13343. };
  13344. Scene.prototype._evaluateActiveMeshes = function () {
  13345. this.activeCamera._activeMeshes.reset();
  13346. this._activeMeshes.reset();
  13347. this._renderingManager.reset();
  13348. this._processedMaterials.reset();
  13349. this._activeParticleSystems.reset();
  13350. this._activeSkeletons.reset();
  13351. this._softwareSkinnedMeshes.reset();
  13352. this._boundingBoxRenderer.reset();
  13353. this._edgesRenderers.reset();
  13354. if (!this._frustumPlanes) {
  13355. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13356. }
  13357. else {
  13358. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13359. }
  13360. // Meshes
  13361. var meshes;
  13362. var len;
  13363. if (this._selectionOctree) {
  13364. var selection = this._selectionOctree.select(this._frustumPlanes);
  13365. meshes = selection.data;
  13366. len = selection.length;
  13367. }
  13368. else {
  13369. len = this.meshes.length;
  13370. meshes = this.meshes;
  13371. }
  13372. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13373. var mesh = meshes[meshIndex];
  13374. if (mesh.isBlocked) {
  13375. continue;
  13376. }
  13377. this._totalVertices += mesh.getTotalVertices();
  13378. if (!mesh.isReady() || !mesh.isEnabled()) {
  13379. continue;
  13380. }
  13381. mesh.computeWorldMatrix();
  13382. // Intersections
  13383. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13384. this._meshesForIntersections.pushNoDuplicate(mesh);
  13385. }
  13386. // Switch to current LOD
  13387. var meshLOD = mesh.getLOD(this.activeCamera);
  13388. if (!meshLOD) {
  13389. continue;
  13390. }
  13391. mesh._preActivate();
  13392. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13393. this._activeMeshes.push(mesh);
  13394. this.activeCamera._activeMeshes.push(mesh);
  13395. mesh._activate(this._renderId);
  13396. this._activeMesh(meshLOD);
  13397. }
  13398. }
  13399. // Particle systems
  13400. var beforeParticlesDate = BABYLON.Tools.Now;
  13401. if (this.particlesEnabled) {
  13402. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13403. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13404. var particleSystem = this.particleSystems[particleIndex];
  13405. if (!particleSystem.isStarted()) {
  13406. continue;
  13407. }
  13408. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13409. this._activeParticleSystems.push(particleSystem);
  13410. particleSystem.animate();
  13411. }
  13412. }
  13413. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13414. }
  13415. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13416. };
  13417. Scene.prototype._activeMesh = function (mesh) {
  13418. if (mesh.skeleton && this.skeletonsEnabled) {
  13419. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13420. if (!mesh.computeBonesUsingShaders) {
  13421. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13422. }
  13423. }
  13424. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13425. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13426. }
  13427. if (mesh._edgesRenderer) {
  13428. this._edgesRenderers.push(mesh._edgesRenderer);
  13429. }
  13430. if (mesh && mesh.subMeshes) {
  13431. // Submeshes Octrees
  13432. var len;
  13433. var subMeshes;
  13434. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13435. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13436. len = intersections.length;
  13437. subMeshes = intersections.data;
  13438. }
  13439. else {
  13440. subMeshes = mesh.subMeshes;
  13441. len = subMeshes.length;
  13442. }
  13443. for (var subIndex = 0; subIndex < len; subIndex++) {
  13444. var subMesh = subMeshes[subIndex];
  13445. this._evaluateSubMesh(subMesh, mesh);
  13446. }
  13447. }
  13448. };
  13449. Scene.prototype.updateTransformMatrix = function (force) {
  13450. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13451. };
  13452. Scene.prototype._renderForCamera = function (camera) {
  13453. var engine = this._engine;
  13454. this.activeCamera = camera;
  13455. if (!this.activeCamera)
  13456. throw new Error("Active camera not set");
  13457. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13458. // Viewport
  13459. engine.setViewport(this.activeCamera.viewport);
  13460. // Camera
  13461. this.resetCachedMaterial();
  13462. this._renderId++;
  13463. this.updateTransformMatrix();
  13464. if (this.beforeCameraRender) {
  13465. this.beforeCameraRender(this.activeCamera);
  13466. }
  13467. // Meshes
  13468. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13469. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13470. this._evaluateActiveMeshes();
  13471. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13472. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13473. // Skeletons
  13474. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13475. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13476. skeleton.prepare();
  13477. }
  13478. // Software skinning
  13479. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13480. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13481. mesh.applySkeleton(mesh.skeleton);
  13482. }
  13483. // Render targets
  13484. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13485. if (this.renderTargetsEnabled) {
  13486. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13487. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13488. var renderTarget = this._renderTargets.data[renderIndex];
  13489. if (renderTarget._shouldRender()) {
  13490. this._renderId++;
  13491. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13492. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13493. }
  13494. }
  13495. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13496. this._renderId++;
  13497. }
  13498. if (this._renderTargets.length > 0) {
  13499. engine.restoreDefaultFramebuffer();
  13500. }
  13501. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13502. // Prepare Frame
  13503. this.postProcessManager._prepareFrame();
  13504. var beforeRenderDate = BABYLON.Tools.Now;
  13505. // Backgrounds
  13506. var layerIndex;
  13507. if (this.layers.length) {
  13508. engine.setDepthBuffer(false);
  13509. var layer;
  13510. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13511. layer = this.layers[layerIndex];
  13512. if (layer.isBackground) {
  13513. layer.render();
  13514. }
  13515. }
  13516. engine.setDepthBuffer(true);
  13517. }
  13518. // Render
  13519. BABYLON.Tools.StartPerformanceCounter("Main render");
  13520. this._renderingManager.render(null, null, true, true);
  13521. BABYLON.Tools.EndPerformanceCounter("Main render");
  13522. // Bounding boxes
  13523. this._boundingBoxRenderer.render();
  13524. // Edges
  13525. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13526. this._edgesRenderers.data[edgesRendererIndex].render();
  13527. }
  13528. // Lens flares
  13529. if (this.lensFlaresEnabled) {
  13530. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13531. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13532. this.lensFlareSystems[lensFlareSystemIndex].render();
  13533. }
  13534. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13535. }
  13536. // Foregrounds
  13537. if (this.layers.length) {
  13538. engine.setDepthBuffer(false);
  13539. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13540. layer = this.layers[layerIndex];
  13541. if (!layer.isBackground) {
  13542. layer.render();
  13543. }
  13544. }
  13545. engine.setDepthBuffer(true);
  13546. }
  13547. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13548. // Finalize frame
  13549. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13550. // Update camera
  13551. this.activeCamera._updateFromScene();
  13552. // Reset some special arrays
  13553. this._renderTargets.reset();
  13554. if (this.afterCameraRender) {
  13555. this.afterCameraRender(this.activeCamera);
  13556. }
  13557. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13558. };
  13559. Scene.prototype._processSubCameras = function (camera) {
  13560. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13561. this._renderForCamera(camera);
  13562. return;
  13563. }
  13564. // rig cameras
  13565. for (var index = 0; index < camera._rigCameras.length; index++) {
  13566. this._renderForCamera(camera._rigCameras[index]);
  13567. }
  13568. this.activeCamera = camera;
  13569. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13570. // Update camera
  13571. this.activeCamera._updateFromScene();
  13572. };
  13573. Scene.prototype._checkIntersections = function () {
  13574. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13575. var sourceMesh = this._meshesForIntersections.data[index];
  13576. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13577. var action = sourceMesh.actionManager.actions[actionIndex];
  13578. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13579. var parameters = action.getTriggerParameter();
  13580. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13581. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13582. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13583. if (areIntersecting && currentIntersectionInProgress === -1) {
  13584. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13585. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13586. sourceMesh._intersectionsInProgress.push(otherMesh);
  13587. }
  13588. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13589. sourceMesh._intersectionsInProgress.push(otherMesh);
  13590. }
  13591. }
  13592. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13593. //They intersected, and now they don't.
  13594. //is this trigger an exit trigger? execute an event.
  13595. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13596. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13597. }
  13598. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13599. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13600. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13601. }
  13602. }
  13603. }
  13604. }
  13605. }
  13606. };
  13607. Scene.prototype.render = function () {
  13608. var startDate = BABYLON.Tools.Now;
  13609. this._particlesDuration = 0;
  13610. this._spritesDuration = 0;
  13611. this._activeParticles = 0;
  13612. this._renderDuration = 0;
  13613. this._renderTargetsDuration = 0;
  13614. this._evaluateActiveMeshesDuration = 0;
  13615. this._totalVertices = 0;
  13616. this._activeIndices = 0;
  13617. this._activeBones = 0;
  13618. this.getEngine().resetDrawCalls();
  13619. this._meshesForIntersections.reset();
  13620. this.resetCachedMaterial();
  13621. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13622. // Actions
  13623. if (this.actionManager) {
  13624. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13625. }
  13626. //Simplification Queue
  13627. if (!this.simplificationQueue.running) {
  13628. this.simplificationQueue.executeNext();
  13629. }
  13630. // Before render
  13631. if (this.beforeRender) {
  13632. this.beforeRender();
  13633. }
  13634. var callbackIndex;
  13635. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13636. this._onBeforeRenderCallbacks[callbackIndex]();
  13637. }
  13638. // Animations
  13639. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13640. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13641. this._animate();
  13642. // Physics
  13643. if (this._physicsEngine) {
  13644. BABYLON.Tools.StartPerformanceCounter("Physics");
  13645. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13646. BABYLON.Tools.EndPerformanceCounter("Physics");
  13647. }
  13648. // Customs render targets
  13649. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13650. var engine = this.getEngine();
  13651. var currentActiveCamera = this.activeCamera;
  13652. if (this.renderTargetsEnabled) {
  13653. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13654. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13655. var renderTarget = this.customRenderTargets[customIndex];
  13656. if (renderTarget._shouldRender()) {
  13657. this._renderId++;
  13658. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13659. if (!this.activeCamera)
  13660. throw new Error("Active camera not set");
  13661. // Viewport
  13662. engine.setViewport(this.activeCamera.viewport);
  13663. // Camera
  13664. this.updateTransformMatrix();
  13665. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13666. }
  13667. }
  13668. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13669. this._renderId++;
  13670. }
  13671. if (this.customRenderTargets.length > 0) {
  13672. engine.restoreDefaultFramebuffer();
  13673. }
  13674. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13675. this.activeCamera = currentActiveCamera;
  13676. // Procedural textures
  13677. if (this.proceduralTexturesEnabled) {
  13678. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13679. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13680. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13681. if (proceduralTexture._shouldRender()) {
  13682. proceduralTexture.render();
  13683. }
  13684. }
  13685. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13686. }
  13687. // Clear
  13688. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13689. // Shadows
  13690. if (this.shadowsEnabled) {
  13691. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13692. var light = this.lights[lightIndex];
  13693. var shadowGenerator = light.getShadowGenerator();
  13694. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13695. this._renderTargets.push(shadowGenerator.getShadowMap());
  13696. }
  13697. }
  13698. }
  13699. // Depth renderer
  13700. if (this._depthRenderer) {
  13701. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13702. }
  13703. // RenderPipeline
  13704. this.postProcessRenderPipelineManager.update();
  13705. // Multi-cameras?
  13706. if (this.activeCameras.length > 0) {
  13707. var currentRenderId = this._renderId;
  13708. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13709. this._renderId = currentRenderId;
  13710. this._processSubCameras(this.activeCameras[cameraIndex]);
  13711. }
  13712. }
  13713. else {
  13714. if (!this.activeCamera) {
  13715. throw new Error("No camera defined");
  13716. }
  13717. this._processSubCameras(this.activeCamera);
  13718. }
  13719. // Intersection checks
  13720. this._checkIntersections();
  13721. // Update the audio listener attached to the camera
  13722. this._updateAudioParameters();
  13723. // After render
  13724. if (this.afterRender) {
  13725. this.afterRender();
  13726. }
  13727. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13728. this._onAfterRenderCallbacks[callbackIndex]();
  13729. }
  13730. // Cleaning
  13731. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13732. this._toBeDisposed.data[index].dispose();
  13733. this._toBeDisposed[index] = null;
  13734. }
  13735. this._toBeDisposed.reset();
  13736. if (this.dumpNextRenderTargets) {
  13737. this.dumpNextRenderTargets = false;
  13738. }
  13739. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13740. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13741. };
  13742. Scene.prototype._updateAudioParameters = function () {
  13743. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13744. return;
  13745. }
  13746. var listeningCamera;
  13747. var audioEngine = BABYLON.Engine.audioEngine;
  13748. if (this.activeCameras.length > 0) {
  13749. listeningCamera = this.activeCameras[0];
  13750. }
  13751. else {
  13752. listeningCamera = this.activeCamera;
  13753. }
  13754. if (listeningCamera && audioEngine.canUseWebAudio) {
  13755. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13756. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13757. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13758. cameraDirection.normalize();
  13759. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13760. var i;
  13761. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13762. var sound = this.mainSoundTrack.soundCollection[i];
  13763. if (sound.useCustomAttenuation) {
  13764. sound.updateDistanceFromListener();
  13765. }
  13766. }
  13767. for (i = 0; i < this.soundTracks.length; i++) {
  13768. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13769. sound = this.soundTracks[i].soundCollection[j];
  13770. if (sound.useCustomAttenuation) {
  13771. sound.updateDistanceFromListener();
  13772. }
  13773. }
  13774. }
  13775. }
  13776. };
  13777. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13778. // Audio
  13779. get: function () {
  13780. return this._audioEnabled;
  13781. },
  13782. set: function (value) {
  13783. this._audioEnabled = value;
  13784. if (this._audioEnabled) {
  13785. this._enableAudio();
  13786. }
  13787. else {
  13788. this._disableAudio();
  13789. }
  13790. },
  13791. enumerable: true,
  13792. configurable: true
  13793. });
  13794. Scene.prototype._disableAudio = function () {
  13795. var i;
  13796. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13797. this.mainSoundTrack.soundCollection[i].pause();
  13798. }
  13799. for (i = 0; i < this.soundTracks.length; i++) {
  13800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13801. this.soundTracks[i].soundCollection[j].pause();
  13802. }
  13803. }
  13804. };
  13805. Scene.prototype._enableAudio = function () {
  13806. var i;
  13807. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13808. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13809. this.mainSoundTrack.soundCollection[i].play();
  13810. }
  13811. }
  13812. for (i = 0; i < this.soundTracks.length; i++) {
  13813. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13814. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13815. this.soundTracks[i].soundCollection[j].play();
  13816. }
  13817. }
  13818. }
  13819. };
  13820. Object.defineProperty(Scene.prototype, "headphone", {
  13821. get: function () {
  13822. return this._headphone;
  13823. },
  13824. set: function (value) {
  13825. this._headphone = value;
  13826. if (this._headphone) {
  13827. this._switchAudioModeForHeadphones();
  13828. }
  13829. else {
  13830. this._switchAudioModeForNormalSpeakers();
  13831. }
  13832. },
  13833. enumerable: true,
  13834. configurable: true
  13835. });
  13836. Scene.prototype._switchAudioModeForHeadphones = function () {
  13837. this.mainSoundTrack.switchPanningModelToHRTF();
  13838. for (var i = 0; i < this.soundTracks.length; i++) {
  13839. this.soundTracks[i].switchPanningModelToHRTF();
  13840. }
  13841. };
  13842. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13843. this.mainSoundTrack.switchPanningModelToEqualPower();
  13844. for (var i = 0; i < this.soundTracks.length; i++) {
  13845. this.soundTracks[i].switchPanningModelToEqualPower();
  13846. }
  13847. };
  13848. Scene.prototype.enableDepthRenderer = function () {
  13849. if (this._depthRenderer) {
  13850. return this._depthRenderer;
  13851. }
  13852. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13853. return this._depthRenderer;
  13854. };
  13855. Scene.prototype.disableDepthRenderer = function () {
  13856. if (!this._depthRenderer) {
  13857. return;
  13858. }
  13859. this._depthRenderer.dispose();
  13860. this._depthRenderer = null;
  13861. };
  13862. Scene.prototype.dispose = function () {
  13863. this.beforeRender = null;
  13864. this.afterRender = null;
  13865. this.skeletons = [];
  13866. this._boundingBoxRenderer.dispose();
  13867. if (this._depthRenderer) {
  13868. this._depthRenderer.dispose();
  13869. }
  13870. // Debug layer
  13871. this.debugLayer.hide();
  13872. // Events
  13873. if (this.onDispose) {
  13874. this.onDispose();
  13875. }
  13876. this._onBeforeRenderCallbacks = [];
  13877. this._onAfterRenderCallbacks = [];
  13878. this.detachControl();
  13879. // Release sounds & sounds tracks
  13880. this.disposeSounds();
  13881. // Detach cameras
  13882. var canvas = this._engine.getRenderingCanvas();
  13883. var index;
  13884. for (index = 0; index < this.cameras.length; index++) {
  13885. this.cameras[index].detachControl(canvas);
  13886. }
  13887. // Release lights
  13888. while (this.lights.length) {
  13889. this.lights[0].dispose();
  13890. }
  13891. // Release meshes
  13892. while (this.meshes.length) {
  13893. this.meshes[0].dispose(true);
  13894. }
  13895. // Release cameras
  13896. while (this.cameras.length) {
  13897. this.cameras[0].dispose();
  13898. }
  13899. // Release materials
  13900. while (this.materials.length) {
  13901. this.materials[0].dispose();
  13902. }
  13903. // Release particles
  13904. while (this.particleSystems.length) {
  13905. this.particleSystems[0].dispose();
  13906. }
  13907. // Release sprites
  13908. while (this.spriteManagers.length) {
  13909. this.spriteManagers[0].dispose();
  13910. }
  13911. // Release layers
  13912. while (this.layers.length) {
  13913. this.layers[0].dispose();
  13914. }
  13915. // Release textures
  13916. while (this.textures.length) {
  13917. this.textures[0].dispose();
  13918. }
  13919. // Post-processes
  13920. this.postProcessManager.dispose();
  13921. // Physics
  13922. if (this._physicsEngine) {
  13923. this.disablePhysicsEngine();
  13924. }
  13925. // Remove from engine
  13926. index = this._engine.scenes.indexOf(this);
  13927. if (index > -1) {
  13928. this._engine.scenes.splice(index, 1);
  13929. }
  13930. this._engine.wipeCaches();
  13931. };
  13932. // Release sounds & sounds tracks
  13933. Scene.prototype.disposeSounds = function () {
  13934. this.mainSoundTrack.dispose();
  13935. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13936. this.soundTracks[scIndex].dispose();
  13937. }
  13938. };
  13939. // Octrees
  13940. Scene.prototype.getWorldExtends = function () {
  13941. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13942. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13943. for (var index = 0; index < this.meshes.length; index++) {
  13944. var mesh = this.meshes[index];
  13945. mesh.computeWorldMatrix(true);
  13946. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13947. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13948. BABYLON.Tools.CheckExtends(minBox, min, max);
  13949. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13950. }
  13951. return {
  13952. min: min,
  13953. max: max
  13954. };
  13955. };
  13956. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13957. if (maxCapacity === void 0) { maxCapacity = 64; }
  13958. if (maxDepth === void 0) { maxDepth = 2; }
  13959. if (!this._selectionOctree) {
  13960. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13961. }
  13962. var worldExtends = this.getWorldExtends();
  13963. // Update octree
  13964. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13965. return this._selectionOctree;
  13966. };
  13967. // Picking
  13968. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13969. var engine = this._engine;
  13970. if (!camera) {
  13971. if (!this.activeCamera)
  13972. throw new Error("Active camera not set");
  13973. camera = this.activeCamera;
  13974. }
  13975. var cameraViewport = camera.viewport;
  13976. var viewport = cameraViewport.toGlobal(engine);
  13977. // Moving coordinates to local viewport world
  13978. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13979. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13980. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13981. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13982. };
  13983. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13984. var pickingInfo = null;
  13985. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13986. var mesh = this.meshes[meshIndex];
  13987. if (predicate) {
  13988. if (!predicate(mesh)) {
  13989. continue;
  13990. }
  13991. }
  13992. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13993. continue;
  13994. }
  13995. var world = mesh.getWorldMatrix();
  13996. var ray = rayFunction(world);
  13997. var result = mesh.intersects(ray, fastCheck);
  13998. if (!result || !result.hit)
  13999. continue;
  14000. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14001. continue;
  14002. pickingInfo = result;
  14003. if (fastCheck) {
  14004. break;
  14005. }
  14006. }
  14007. return pickingInfo || new BABYLON.PickingInfo();
  14008. };
  14009. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14010. var _this = this;
  14011. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14012. /// <param name="x">X position on screen</param>
  14013. /// <param name="y">Y position on screen</param>
  14014. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14015. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14016. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14017. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14018. };
  14019. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14020. var _this = this;
  14021. return this._internalPick(function (world) {
  14022. if (!_this._pickWithRayInverseMatrix) {
  14023. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14024. }
  14025. world.invertToRef(_this._pickWithRayInverseMatrix);
  14026. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14027. }, predicate, fastCheck);
  14028. };
  14029. Scene.prototype.setPointerOverMesh = function (mesh) {
  14030. if (this._pointerOverMesh === mesh) {
  14031. return;
  14032. }
  14033. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14034. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14035. }
  14036. this._pointerOverMesh = mesh;
  14037. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14038. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14039. }
  14040. };
  14041. Scene.prototype.getPointerOverMesh = function () {
  14042. return this._pointerOverMesh;
  14043. };
  14044. // Physics
  14045. Scene.prototype.getPhysicsEngine = function () {
  14046. return this._physicsEngine;
  14047. };
  14048. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14049. if (this._physicsEngine) {
  14050. return true;
  14051. }
  14052. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14053. if (!this._physicsEngine.isSupported()) {
  14054. this._physicsEngine = null;
  14055. return false;
  14056. }
  14057. this._physicsEngine._initialize(gravity);
  14058. return true;
  14059. };
  14060. Scene.prototype.disablePhysicsEngine = function () {
  14061. if (!this._physicsEngine) {
  14062. return;
  14063. }
  14064. this._physicsEngine.dispose();
  14065. this._physicsEngine = undefined;
  14066. };
  14067. Scene.prototype.isPhysicsEnabled = function () {
  14068. return this._physicsEngine !== undefined;
  14069. };
  14070. Scene.prototype.setGravity = function (gravity) {
  14071. if (!this._physicsEngine) {
  14072. return;
  14073. }
  14074. this._physicsEngine._setGravity(gravity);
  14075. };
  14076. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14077. if (parts.parts) {
  14078. options = parts;
  14079. parts = parts.parts;
  14080. }
  14081. if (!this._physicsEngine) {
  14082. return null;
  14083. }
  14084. for (var index = 0; index < parts.length; index++) {
  14085. var mesh = parts[index].mesh;
  14086. mesh._physicImpostor = parts[index].impostor;
  14087. mesh._physicsMass = options.mass / parts.length;
  14088. mesh._physicsFriction = options.friction;
  14089. mesh._physicRestitution = options.restitution;
  14090. }
  14091. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14092. };
  14093. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14094. for (var index = 0; index < compound.parts.length; index++) {
  14095. var mesh = compound.parts[index].mesh;
  14096. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14097. this._physicsEngine._unregisterMesh(mesh);
  14098. }
  14099. };
  14100. // Misc.
  14101. Scene.prototype.createDefaultCameraOrLight = function () {
  14102. // Light
  14103. if (this.lights.length === 0) {
  14104. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14105. }
  14106. // Camera
  14107. if (!this.activeCamera) {
  14108. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14109. // Compute position
  14110. var worldExtends = this.getWorldExtends();
  14111. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14112. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14113. camera.setTarget(worldCenter);
  14114. this.activeCamera = camera;
  14115. }
  14116. };
  14117. // Tags
  14118. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14119. if (tagsQuery === undefined) {
  14120. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14121. return list;
  14122. }
  14123. var listByTags = [];
  14124. forEach = forEach || (function (item) { return; });
  14125. for (var i in list) {
  14126. var item = list[i];
  14127. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14128. listByTags.push(item);
  14129. forEach(item);
  14130. }
  14131. }
  14132. return listByTags;
  14133. };
  14134. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14135. return this._getByTags(this.meshes, tagsQuery, forEach);
  14136. };
  14137. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14138. return this._getByTags(this.cameras, tagsQuery, forEach);
  14139. };
  14140. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14141. return this._getByTags(this.lights, tagsQuery, forEach);
  14142. };
  14143. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14144. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14145. };
  14146. // Statics
  14147. Scene._FOGMODE_NONE = 0;
  14148. Scene._FOGMODE_EXP = 1;
  14149. Scene._FOGMODE_EXP2 = 2;
  14150. Scene._FOGMODE_LINEAR = 3;
  14151. Scene.MinDeltaTime = 1.0;
  14152. Scene.MaxDeltaTime = 1000.0;
  14153. return Scene;
  14154. })();
  14155. BABYLON.Scene = Scene;
  14156. })(BABYLON || (BABYLON = {}));
  14157. var BABYLON;
  14158. (function (BABYLON) {
  14159. var VertexBuffer = (function () {
  14160. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14161. if (engine instanceof BABYLON.Mesh) {
  14162. this._engine = engine.getScene().getEngine();
  14163. }
  14164. else {
  14165. this._engine = engine;
  14166. }
  14167. this._updatable = updatable;
  14168. this._data = data;
  14169. if (!postponeInternalCreation) {
  14170. this.create();
  14171. }
  14172. this._kind = kind;
  14173. if (stride) {
  14174. this._strideSize = stride;
  14175. return;
  14176. }
  14177. // Deduce stride from kind
  14178. switch (kind) {
  14179. case VertexBuffer.PositionKind:
  14180. this._strideSize = 3;
  14181. break;
  14182. case VertexBuffer.NormalKind:
  14183. this._strideSize = 3;
  14184. break;
  14185. case VertexBuffer.UVKind:
  14186. case VertexBuffer.UV2Kind:
  14187. case VertexBuffer.UV3Kind:
  14188. case VertexBuffer.UV4Kind:
  14189. case VertexBuffer.UV5Kind:
  14190. case VertexBuffer.UV6Kind:
  14191. this._strideSize = 2;
  14192. break;
  14193. case VertexBuffer.ColorKind:
  14194. this._strideSize = 4;
  14195. break;
  14196. case VertexBuffer.MatricesIndicesKind:
  14197. this._strideSize = 4;
  14198. break;
  14199. case VertexBuffer.MatricesWeightsKind:
  14200. this._strideSize = 4;
  14201. break;
  14202. }
  14203. }
  14204. // Properties
  14205. VertexBuffer.prototype.isUpdatable = function () {
  14206. return this._updatable;
  14207. };
  14208. VertexBuffer.prototype.getData = function () {
  14209. return this._data;
  14210. };
  14211. VertexBuffer.prototype.getBuffer = function () {
  14212. return this._buffer;
  14213. };
  14214. VertexBuffer.prototype.getStrideSize = function () {
  14215. return this._strideSize;
  14216. };
  14217. // Methods
  14218. VertexBuffer.prototype.create = function (data) {
  14219. if (!data && this._buffer) {
  14220. return; // nothing to do
  14221. }
  14222. data = data || this._data;
  14223. if (!this._buffer) {
  14224. if (this._updatable) {
  14225. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14226. }
  14227. else {
  14228. this._buffer = this._engine.createVertexBuffer(data);
  14229. }
  14230. }
  14231. if (this._updatable) {
  14232. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14233. this._data = data;
  14234. }
  14235. };
  14236. VertexBuffer.prototype.update = function (data) {
  14237. this.create(data);
  14238. };
  14239. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14240. if (!this._buffer) {
  14241. return;
  14242. }
  14243. if (this._updatable) {
  14244. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14245. this._data = null;
  14246. }
  14247. };
  14248. VertexBuffer.prototype.dispose = function () {
  14249. if (!this._buffer) {
  14250. return;
  14251. }
  14252. if (this._engine._releaseBuffer(this._buffer)) {
  14253. this._buffer = null;
  14254. }
  14255. };
  14256. Object.defineProperty(VertexBuffer, "PositionKind", {
  14257. get: function () {
  14258. return VertexBuffer._PositionKind;
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(VertexBuffer, "NormalKind", {
  14264. get: function () {
  14265. return VertexBuffer._NormalKind;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(VertexBuffer, "UVKind", {
  14271. get: function () {
  14272. return VertexBuffer._UVKind;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14278. get: function () {
  14279. return VertexBuffer._UV2Kind;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14285. get: function () {
  14286. return VertexBuffer._UV3Kind;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14292. get: function () {
  14293. return VertexBuffer._UV4Kind;
  14294. },
  14295. enumerable: true,
  14296. configurable: true
  14297. });
  14298. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14299. get: function () {
  14300. return VertexBuffer._UV5Kind;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14306. get: function () {
  14307. return VertexBuffer._UV6Kind;
  14308. },
  14309. enumerable: true,
  14310. configurable: true
  14311. });
  14312. Object.defineProperty(VertexBuffer, "ColorKind", {
  14313. get: function () {
  14314. return VertexBuffer._ColorKind;
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14320. get: function () {
  14321. return VertexBuffer._MatricesIndicesKind;
  14322. },
  14323. enumerable: true,
  14324. configurable: true
  14325. });
  14326. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14327. get: function () {
  14328. return VertexBuffer._MatricesWeightsKind;
  14329. },
  14330. enumerable: true,
  14331. configurable: true
  14332. });
  14333. // Enums
  14334. VertexBuffer._PositionKind = "position";
  14335. VertexBuffer._NormalKind = "normal";
  14336. VertexBuffer._UVKind = "uv";
  14337. VertexBuffer._UV2Kind = "uv2";
  14338. VertexBuffer._UV3Kind = "uv3";
  14339. VertexBuffer._UV4Kind = "uv4";
  14340. VertexBuffer._UV5Kind = "uv5";
  14341. VertexBuffer._UV6Kind = "uv6";
  14342. VertexBuffer._ColorKind = "color";
  14343. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14344. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14345. return VertexBuffer;
  14346. })();
  14347. BABYLON.VertexBuffer = VertexBuffer;
  14348. })(BABYLON || (BABYLON = {}));
  14349. var BABYLON;
  14350. (function (BABYLON) {
  14351. /**
  14352. * Creates an instance based on a source mesh.
  14353. */
  14354. var InstancedMesh = (function (_super) {
  14355. __extends(InstancedMesh, _super);
  14356. function InstancedMesh(name, source) {
  14357. _super.call(this, name, source.getScene());
  14358. source.instances.push(this);
  14359. this._sourceMesh = source;
  14360. this.position.copyFrom(source.position);
  14361. this.rotation.copyFrom(source.rotation);
  14362. this.scaling.copyFrom(source.scaling);
  14363. if (source.rotationQuaternion) {
  14364. this.rotationQuaternion = source.rotationQuaternion.clone();
  14365. }
  14366. this.infiniteDistance = source.infiniteDistance;
  14367. this.setPivotMatrix(source.getPivotMatrix());
  14368. this.refreshBoundingInfo();
  14369. this._syncSubMeshes();
  14370. }
  14371. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14372. // Methods
  14373. get: function () {
  14374. return this._sourceMesh.receiveShadows;
  14375. },
  14376. enumerable: true,
  14377. configurable: true
  14378. });
  14379. Object.defineProperty(InstancedMesh.prototype, "material", {
  14380. get: function () {
  14381. return this._sourceMesh.material;
  14382. },
  14383. enumerable: true,
  14384. configurable: true
  14385. });
  14386. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14387. get: function () {
  14388. return this._sourceMesh.visibility;
  14389. },
  14390. enumerable: true,
  14391. configurable: true
  14392. });
  14393. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14394. get: function () {
  14395. return this._sourceMesh.skeleton;
  14396. },
  14397. enumerable: true,
  14398. configurable: true
  14399. });
  14400. InstancedMesh.prototype.getTotalVertices = function () {
  14401. return this._sourceMesh.getTotalVertices();
  14402. };
  14403. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14404. get: function () {
  14405. return this._sourceMesh;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. InstancedMesh.prototype.getVerticesData = function (kind) {
  14411. return this._sourceMesh.getVerticesData(kind);
  14412. };
  14413. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14414. return this._sourceMesh.isVerticesDataPresent(kind);
  14415. };
  14416. InstancedMesh.prototype.getIndices = function () {
  14417. return this._sourceMesh.getIndices();
  14418. };
  14419. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14420. get: function () {
  14421. return this._sourceMesh._positions;
  14422. },
  14423. enumerable: true,
  14424. configurable: true
  14425. });
  14426. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14427. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14428. if (data) {
  14429. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14430. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14431. }
  14432. this._updateBoundingInfo();
  14433. };
  14434. InstancedMesh.prototype._preActivate = function () {
  14435. if (this._currentLOD) {
  14436. this._currentLOD._preActivate();
  14437. }
  14438. };
  14439. InstancedMesh.prototype._activate = function (renderId) {
  14440. if (this._currentLOD) {
  14441. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14442. }
  14443. };
  14444. InstancedMesh.prototype.getLOD = function (camera) {
  14445. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14446. if (this._currentLOD === this.sourceMesh) {
  14447. return this;
  14448. }
  14449. return this._currentLOD;
  14450. };
  14451. InstancedMesh.prototype._syncSubMeshes = function () {
  14452. this.releaseSubMeshes();
  14453. if (this._sourceMesh.subMeshes) {
  14454. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14455. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14456. }
  14457. }
  14458. };
  14459. InstancedMesh.prototype._generatePointsArray = function () {
  14460. return this._sourceMesh._generatePointsArray();
  14461. };
  14462. // Clone
  14463. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14464. var result = this._sourceMesh.createInstance(name);
  14465. // Deep copy
  14466. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14467. // Bounding info
  14468. this.refreshBoundingInfo();
  14469. // Parent
  14470. if (newParent) {
  14471. result.parent = newParent;
  14472. }
  14473. if (!doNotCloneChildren) {
  14474. // Children
  14475. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14476. var mesh = this.getScene().meshes[index];
  14477. if (mesh.parent === this) {
  14478. mesh.clone(mesh.name, result);
  14479. }
  14480. }
  14481. }
  14482. result.computeWorldMatrix(true);
  14483. return result;
  14484. };
  14485. // Dispoe
  14486. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14487. // Remove from mesh
  14488. var index = this._sourceMesh.instances.indexOf(this);
  14489. this._sourceMesh.instances.splice(index, 1);
  14490. _super.prototype.dispose.call(this, doNotRecurse);
  14491. };
  14492. return InstancedMesh;
  14493. })(BABYLON.AbstractMesh);
  14494. BABYLON.InstancedMesh = InstancedMesh;
  14495. })(BABYLON || (BABYLON = {}));
  14496. var BABYLON;
  14497. (function (BABYLON) {
  14498. var _InstancesBatch = (function () {
  14499. function _InstancesBatch() {
  14500. this.mustReturn = false;
  14501. this.visibleInstances = new Array();
  14502. this.renderSelf = new Array();
  14503. }
  14504. return _InstancesBatch;
  14505. })();
  14506. BABYLON._InstancesBatch = _InstancesBatch;
  14507. var Mesh = (function (_super) {
  14508. __extends(Mesh, _super);
  14509. /**
  14510. * @constructor
  14511. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14512. * @param {Scene} scene - The scene to add this mesh to.
  14513. * @param {Node} parent - The parent of this mesh, if it has one
  14514. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14515. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14516. * When false, achieved by calling a clone(), also passing False.
  14517. * This will make creation of children, recursive.
  14518. */
  14519. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14520. if (parent === void 0) { parent = null; }
  14521. _super.call(this, name, scene);
  14522. // Members
  14523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14524. this.instances = new Array();
  14525. this._LODLevels = new Array();
  14526. this._onBeforeRenderCallbacks = new Array();
  14527. this._onAfterRenderCallbacks = new Array();
  14528. this._visibleInstances = {};
  14529. this._renderIdForInstances = new Array();
  14530. this._batchCache = new _InstancesBatch();
  14531. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14532. this._sideOrientation = Mesh._DEFAULTSIDE;
  14533. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14534. if (source) {
  14535. // Geometry
  14536. if (source._geometry) {
  14537. source._geometry.applyToMesh(this);
  14538. }
  14539. // Deep copy
  14540. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14541. this.id = name + "." + source.id;
  14542. // Material
  14543. this.material = source.material;
  14544. if (!doNotCloneChildren) {
  14545. // Children
  14546. for (var index = 0; index < scene.meshes.length; index++) {
  14547. var mesh = scene.meshes[index];
  14548. if (mesh.parent === source) {
  14549. // doNotCloneChildren is always going to be False
  14550. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14551. }
  14552. }
  14553. }
  14554. // Particles
  14555. for (index = 0; index < scene.particleSystems.length; index++) {
  14556. var system = scene.particleSystems[index];
  14557. if (system.emitter === source) {
  14558. system.clone(system.name, this);
  14559. }
  14560. }
  14561. this.computeWorldMatrix(true);
  14562. }
  14563. // Parent
  14564. if (parent !== null) {
  14565. this.parent = parent;
  14566. }
  14567. }
  14568. Object.defineProperty(Mesh, "FRONTSIDE", {
  14569. get: function () {
  14570. return Mesh._FRONTSIDE;
  14571. },
  14572. enumerable: true,
  14573. configurable: true
  14574. });
  14575. Object.defineProperty(Mesh, "BACKSIDE", {
  14576. get: function () {
  14577. return Mesh._BACKSIDE;
  14578. },
  14579. enumerable: true,
  14580. configurable: true
  14581. });
  14582. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14583. get: function () {
  14584. return Mesh._DOUBLESIDE;
  14585. },
  14586. enumerable: true,
  14587. configurable: true
  14588. });
  14589. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14590. get: function () {
  14591. return Mesh._DEFAULTSIDE;
  14592. },
  14593. enumerable: true,
  14594. configurable: true
  14595. });
  14596. Object.defineProperty(Mesh, "NO_CAP", {
  14597. get: function () {
  14598. return Mesh._NO_CAP;
  14599. },
  14600. enumerable: true,
  14601. configurable: true
  14602. });
  14603. Object.defineProperty(Mesh, "CAP_START", {
  14604. get: function () {
  14605. return Mesh._CAP_START;
  14606. },
  14607. enumerable: true,
  14608. configurable: true
  14609. });
  14610. Object.defineProperty(Mesh, "CAP_END", {
  14611. get: function () {
  14612. return Mesh._CAP_END;
  14613. },
  14614. enumerable: true,
  14615. configurable: true
  14616. });
  14617. Object.defineProperty(Mesh, "CAP_ALL", {
  14618. get: function () {
  14619. return Mesh._CAP_ALL;
  14620. },
  14621. enumerable: true,
  14622. configurable: true
  14623. });
  14624. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14625. // Methods
  14626. get: function () {
  14627. return this._LODLevels.length > 0;
  14628. },
  14629. enumerable: true,
  14630. configurable: true
  14631. });
  14632. Mesh.prototype._sortLODLevels = function () {
  14633. this._LODLevels.sort(function (a, b) {
  14634. if (a.distance < b.distance) {
  14635. return 1;
  14636. }
  14637. if (a.distance > b.distance) {
  14638. return -1;
  14639. }
  14640. return 0;
  14641. });
  14642. };
  14643. /**
  14644. * Add a mesh as LOD level triggered at the given distance.
  14645. * @param {number} distance - the distance from the center of the object to show this level
  14646. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14647. * @return {BABYLON.Mesh} this mesh (for chaining)
  14648. */
  14649. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14650. if (mesh && mesh._masterMesh) {
  14651. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14652. return this;
  14653. }
  14654. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14655. this._LODLevels.push(level);
  14656. if (mesh) {
  14657. mesh._masterMesh = this;
  14658. }
  14659. this._sortLODLevels();
  14660. return this;
  14661. };
  14662. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14663. for (var index = 0; index < this._LODLevels.length; index++) {
  14664. var level = this._LODLevels[index];
  14665. if (level.distance === distance) {
  14666. return level.mesh;
  14667. }
  14668. }
  14669. return null;
  14670. };
  14671. /**
  14672. * Remove a mesh from the LOD array
  14673. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14674. * @return {BABYLON.Mesh} this mesh (for chaining)
  14675. */
  14676. Mesh.prototype.removeLODLevel = function (mesh) {
  14677. for (var index = 0; index < this._LODLevels.length; index++) {
  14678. if (this._LODLevels[index].mesh === mesh) {
  14679. this._LODLevels.splice(index, 1);
  14680. if (mesh) {
  14681. mesh._masterMesh = null;
  14682. }
  14683. }
  14684. }
  14685. this._sortLODLevels();
  14686. return this;
  14687. };
  14688. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14689. if (!this._LODLevels || this._LODLevels.length === 0) {
  14690. return this;
  14691. }
  14692. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14693. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14694. if (this.onLODLevelSelection) {
  14695. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14696. }
  14697. return this;
  14698. }
  14699. for (var index = 0; index < this._LODLevels.length; index++) {
  14700. var level = this._LODLevels[index];
  14701. if (level.distance < distanceToCamera) {
  14702. if (level.mesh) {
  14703. level.mesh._preActivate();
  14704. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14705. }
  14706. if (this.onLODLevelSelection) {
  14707. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14708. }
  14709. return level.mesh;
  14710. }
  14711. }
  14712. if (this.onLODLevelSelection) {
  14713. this.onLODLevelSelection(distanceToCamera, this, this);
  14714. }
  14715. return this;
  14716. };
  14717. Object.defineProperty(Mesh.prototype, "geometry", {
  14718. get: function () {
  14719. return this._geometry;
  14720. },
  14721. enumerable: true,
  14722. configurable: true
  14723. });
  14724. Mesh.prototype.getTotalVertices = function () {
  14725. if (!this._geometry) {
  14726. return 0;
  14727. }
  14728. return this._geometry.getTotalVertices();
  14729. };
  14730. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14731. if (!this._geometry) {
  14732. return null;
  14733. }
  14734. return this._geometry.getVerticesData(kind, copyWhenShared);
  14735. };
  14736. Mesh.prototype.getVertexBuffer = function (kind) {
  14737. if (!this._geometry) {
  14738. return undefined;
  14739. }
  14740. return this._geometry.getVertexBuffer(kind);
  14741. };
  14742. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14743. if (!this._geometry) {
  14744. if (this._delayInfo) {
  14745. return this._delayInfo.indexOf(kind) !== -1;
  14746. }
  14747. return false;
  14748. }
  14749. return this._geometry.isVerticesDataPresent(kind);
  14750. };
  14751. Mesh.prototype.getVerticesDataKinds = function () {
  14752. if (!this._geometry) {
  14753. var result = [];
  14754. if (this._delayInfo) {
  14755. for (var kind in this._delayInfo) {
  14756. result.push(kind);
  14757. }
  14758. }
  14759. return result;
  14760. }
  14761. return this._geometry.getVerticesDataKinds();
  14762. };
  14763. Mesh.prototype.getTotalIndices = function () {
  14764. if (!this._geometry) {
  14765. return 0;
  14766. }
  14767. return this._geometry.getTotalIndices();
  14768. };
  14769. Mesh.prototype.getIndices = function (copyWhenShared) {
  14770. if (!this._geometry) {
  14771. return [];
  14772. }
  14773. return this._geometry.getIndices(copyWhenShared);
  14774. };
  14775. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14776. get: function () {
  14777. return this._masterMesh !== null && this._masterMesh !== undefined;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Mesh.prototype.isReady = function () {
  14783. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14784. return false;
  14785. }
  14786. return _super.prototype.isReady.call(this);
  14787. };
  14788. Mesh.prototype.isDisposed = function () {
  14789. return this._isDisposed;
  14790. };
  14791. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14792. get: function () {
  14793. return this._sideOrientation;
  14794. },
  14795. set: function (sideO) {
  14796. this._sideOrientation = sideO;
  14797. },
  14798. enumerable: true,
  14799. configurable: true
  14800. });
  14801. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14802. get: function () {
  14803. return this._areNormalsFrozen;
  14804. },
  14805. enumerable: true,
  14806. configurable: true
  14807. });
  14808. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14809. Mesh.prototype.freezeNormals = function () {
  14810. this._areNormalsFrozen = true;
  14811. };
  14812. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14813. Mesh.prototype.unfreezeNormals = function () {
  14814. this._areNormalsFrozen = false;
  14815. };
  14816. // Methods
  14817. Mesh.prototype._preActivate = function () {
  14818. var sceneRenderId = this.getScene().getRenderId();
  14819. if (this._preActivateId === sceneRenderId) {
  14820. return;
  14821. }
  14822. this._preActivateId = sceneRenderId;
  14823. this._visibleInstances = null;
  14824. };
  14825. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14826. if (!this._visibleInstances) {
  14827. this._visibleInstances = {};
  14828. this._visibleInstances.defaultRenderId = renderId;
  14829. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14830. }
  14831. if (!this._visibleInstances[renderId]) {
  14832. this._visibleInstances[renderId] = new Array();
  14833. }
  14834. this._visibleInstances[renderId].push(instance);
  14835. };
  14836. Mesh.prototype.refreshBoundingInfo = function () {
  14837. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14838. if (data) {
  14839. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14840. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14841. }
  14842. if (this.subMeshes) {
  14843. for (var index = 0; index < this.subMeshes.length; index++) {
  14844. this.subMeshes[index].refreshBoundingInfo();
  14845. }
  14846. }
  14847. this._updateBoundingInfo();
  14848. };
  14849. Mesh.prototype._createGlobalSubMesh = function () {
  14850. var totalVertices = this.getTotalVertices();
  14851. if (!totalVertices || !this.getIndices()) {
  14852. return null;
  14853. }
  14854. this.releaseSubMeshes();
  14855. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14856. };
  14857. Mesh.prototype.subdivide = function (count) {
  14858. if (count < 1) {
  14859. return;
  14860. }
  14861. var totalIndices = this.getTotalIndices();
  14862. var subdivisionSize = (totalIndices / count) | 0;
  14863. var offset = 0;
  14864. // Ensure that subdivisionSize is a multiple of 3
  14865. while (subdivisionSize % 3 !== 0) {
  14866. subdivisionSize++;
  14867. }
  14868. this.releaseSubMeshes();
  14869. for (var index = 0; index < count; index++) {
  14870. if (offset >= totalIndices) {
  14871. break;
  14872. }
  14873. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14874. offset += subdivisionSize;
  14875. }
  14876. this.synchronizeInstances();
  14877. };
  14878. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14879. if (kind instanceof Array) {
  14880. var temp = data;
  14881. data = kind;
  14882. kind = temp;
  14883. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14884. }
  14885. if (!this._geometry) {
  14886. var vertexData = new BABYLON.VertexData();
  14887. vertexData.set(data, kind);
  14888. var scene = this.getScene();
  14889. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14890. }
  14891. else {
  14892. this._geometry.setVerticesData(kind, data, updatable, stride);
  14893. }
  14894. };
  14895. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14896. if (!this._geometry) {
  14897. return;
  14898. }
  14899. if (!makeItUnique) {
  14900. this._geometry.updateVerticesData(kind, data, updateExtends);
  14901. }
  14902. else {
  14903. this.makeGeometryUnique();
  14904. this.updateVerticesData(kind, data, updateExtends, false);
  14905. }
  14906. };
  14907. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14908. if (!this._geometry) {
  14909. return;
  14910. }
  14911. if (!makeItUnique) {
  14912. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14913. }
  14914. else {
  14915. this.makeGeometryUnique();
  14916. this.updateVerticesDataDirectly(kind, data, offset, false);
  14917. }
  14918. };
  14919. // Mesh positions update function :
  14920. // updates the mesh positions according to the positionFunction returned values.
  14921. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14922. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14923. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14924. if (computeNormals === void 0) { computeNormals = true; }
  14925. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14926. positionFunction(positions);
  14927. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14928. if (computeNormals) {
  14929. var indices = this.getIndices();
  14930. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14931. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14932. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14933. }
  14934. };
  14935. Mesh.prototype.makeGeometryUnique = function () {
  14936. if (!this._geometry) {
  14937. return;
  14938. }
  14939. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14940. geometry.applyToMesh(this);
  14941. };
  14942. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14943. if (!this._geometry) {
  14944. var vertexData = new BABYLON.VertexData();
  14945. vertexData.indices = indices;
  14946. var scene = this.getScene();
  14947. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14948. }
  14949. else {
  14950. this._geometry.setIndices(indices, totalVertices);
  14951. }
  14952. };
  14953. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14954. var engine = this.getScene().getEngine();
  14955. // Wireframe
  14956. var indexToBind;
  14957. switch (fillMode) {
  14958. case BABYLON.Material.PointFillMode:
  14959. indexToBind = null;
  14960. break;
  14961. case BABYLON.Material.WireFrameFillMode:
  14962. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14963. break;
  14964. default:
  14965. case BABYLON.Material.TriangleFillMode:
  14966. indexToBind = this._geometry.getIndexBuffer();
  14967. break;
  14968. }
  14969. // VBOs
  14970. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14971. };
  14972. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14973. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14974. return;
  14975. }
  14976. var engine = this.getScene().getEngine();
  14977. // Draw order
  14978. switch (fillMode) {
  14979. case BABYLON.Material.PointFillMode:
  14980. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14981. break;
  14982. case BABYLON.Material.WireFrameFillMode:
  14983. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14984. break;
  14985. default:
  14986. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14987. }
  14988. };
  14989. Mesh.prototype.registerBeforeRender = function (func) {
  14990. this._onBeforeRenderCallbacks.push(func);
  14991. };
  14992. Mesh.prototype.unregisterBeforeRender = function (func) {
  14993. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14994. if (index > -1) {
  14995. this._onBeforeRenderCallbacks.splice(index, 1);
  14996. }
  14997. };
  14998. Mesh.prototype.registerAfterRender = function (func) {
  14999. this._onAfterRenderCallbacks.push(func);
  15000. };
  15001. Mesh.prototype.unregisterAfterRender = function (func) {
  15002. var index = this._onAfterRenderCallbacks.indexOf(func);
  15003. if (index > -1) {
  15004. this._onAfterRenderCallbacks.splice(index, 1);
  15005. }
  15006. };
  15007. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15008. var scene = this.getScene();
  15009. this._batchCache.mustReturn = false;
  15010. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15011. this._batchCache.visibleInstances[subMeshId] = null;
  15012. if (this._visibleInstances) {
  15013. var currentRenderId = scene.getRenderId();
  15014. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15015. var selfRenderId = this._renderId;
  15016. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15017. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15018. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15019. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15020. }
  15021. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15022. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15023. this._batchCache.mustReturn = true;
  15024. return this._batchCache;
  15025. }
  15026. if (currentRenderId !== selfRenderId) {
  15027. this._batchCache.renderSelf[subMeshId] = false;
  15028. }
  15029. }
  15030. this._renderIdForInstances[subMeshId] = currentRenderId;
  15031. }
  15032. return this._batchCache;
  15033. };
  15034. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15035. var visibleInstances = batch.visibleInstances[subMesh._id];
  15036. var matricesCount = visibleInstances.length + 1;
  15037. var bufferSize = matricesCount * 16 * 4;
  15038. while (this._instancesBufferSize < bufferSize) {
  15039. this._instancesBufferSize *= 2;
  15040. }
  15041. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15042. if (this._worldMatricesInstancesBuffer) {
  15043. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15044. }
  15045. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15046. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15047. }
  15048. var offset = 0;
  15049. var instancesCount = 0;
  15050. var world = this.getWorldMatrix();
  15051. if (batch.renderSelf[subMesh._id]) {
  15052. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15053. offset += 16;
  15054. instancesCount++;
  15055. }
  15056. if (visibleInstances) {
  15057. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15058. var instance = visibleInstances[instanceIndex];
  15059. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15060. offset += 16;
  15061. instancesCount++;
  15062. }
  15063. }
  15064. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15065. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15066. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15067. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15068. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15069. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15070. this._draw(subMesh, fillMode, instancesCount);
  15071. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15072. };
  15073. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15074. var scene = this.getScene();
  15075. var engine = scene.getEngine();
  15076. if (hardwareInstancedRendering) {
  15077. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15078. }
  15079. else {
  15080. if (batch.renderSelf[subMesh._id]) {
  15081. // Draw
  15082. if (onBeforeDraw) {
  15083. onBeforeDraw(false, this.getWorldMatrix());
  15084. }
  15085. this._draw(subMesh, fillMode);
  15086. }
  15087. if (batch.visibleInstances[subMesh._id]) {
  15088. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15089. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15090. // World
  15091. var world = instance.getWorldMatrix();
  15092. if (onBeforeDraw) {
  15093. onBeforeDraw(true, world);
  15094. }
  15095. // Draw
  15096. this._draw(subMesh, fillMode);
  15097. }
  15098. }
  15099. }
  15100. };
  15101. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15102. var scene = this.getScene();
  15103. // Managing instances
  15104. var batch = this._getInstancesRenderList(subMesh._id);
  15105. if (batch.mustReturn) {
  15106. return;
  15107. }
  15108. // Checking geometry state
  15109. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15110. return;
  15111. }
  15112. var callbackIndex;
  15113. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15114. this._onBeforeRenderCallbacks[callbackIndex](this);
  15115. }
  15116. var engine = scene.getEngine();
  15117. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15118. // Material
  15119. var effectiveMaterial = subMesh.getMaterial();
  15120. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15121. return;
  15122. }
  15123. // Outline - step 1
  15124. var savedDepthWrite = engine.getDepthWrite();
  15125. if (this.renderOutline) {
  15126. engine.setDepthWrite(false);
  15127. scene.getOutlineRenderer().render(subMesh, batch);
  15128. engine.setDepthWrite(savedDepthWrite);
  15129. }
  15130. effectiveMaterial._preBind();
  15131. var effect = effectiveMaterial.getEffect();
  15132. // Bind
  15133. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15134. this._bind(subMesh, effect, fillMode);
  15135. var world = this.getWorldMatrix();
  15136. effectiveMaterial.bind(world, this);
  15137. // Alpha mode
  15138. if (enableAlphaMode) {
  15139. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15140. }
  15141. // Draw
  15142. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15143. if (isInstance) {
  15144. effectiveMaterial.bindOnlyWorldMatrix(world);
  15145. }
  15146. });
  15147. // Unbind
  15148. effectiveMaterial.unbind();
  15149. // Outline - step 2
  15150. if (this.renderOutline && savedDepthWrite) {
  15151. engine.setDepthWrite(true);
  15152. engine.setColorWrite(false);
  15153. scene.getOutlineRenderer().render(subMesh, batch);
  15154. engine.setColorWrite(true);
  15155. }
  15156. // Overlay
  15157. if (this.renderOverlay) {
  15158. var currentMode = engine.getAlphaMode();
  15159. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15160. scene.getOutlineRenderer().render(subMesh, batch, true);
  15161. engine.setAlphaMode(currentMode);
  15162. }
  15163. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15164. this._onAfterRenderCallbacks[callbackIndex](this);
  15165. }
  15166. };
  15167. Mesh.prototype.getEmittedParticleSystems = function () {
  15168. var results = new Array();
  15169. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15170. var particleSystem = this.getScene().particleSystems[index];
  15171. if (particleSystem.emitter === this) {
  15172. results.push(particleSystem);
  15173. }
  15174. }
  15175. return results;
  15176. };
  15177. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15178. var results = new Array();
  15179. var descendants = this.getDescendants();
  15180. descendants.push(this);
  15181. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15182. var particleSystem = this.getScene().particleSystems[index];
  15183. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15184. results.push(particleSystem);
  15185. }
  15186. }
  15187. return results;
  15188. };
  15189. Mesh.prototype.getChildren = function () {
  15190. var results = [];
  15191. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15192. var mesh = this.getScene().meshes[index];
  15193. if (mesh.parent === this) {
  15194. results.push(mesh);
  15195. }
  15196. }
  15197. return results;
  15198. };
  15199. Mesh.prototype._checkDelayState = function () {
  15200. var _this = this;
  15201. var that = this;
  15202. var scene = this.getScene();
  15203. if (this._geometry) {
  15204. this._geometry.load(scene);
  15205. }
  15206. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15207. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15208. scene._addPendingData(that);
  15209. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15210. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15211. if (data instanceof ArrayBuffer) {
  15212. _this._delayLoadingFunction(data, _this);
  15213. }
  15214. else {
  15215. _this._delayLoadingFunction(JSON.parse(data), _this);
  15216. }
  15217. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15218. scene._removePendingData(_this);
  15219. }, function () { }, scene.database, getBinaryData);
  15220. }
  15221. };
  15222. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15223. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15224. return false;
  15225. }
  15226. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15227. return false;
  15228. }
  15229. this._checkDelayState();
  15230. return true;
  15231. };
  15232. Mesh.prototype.setMaterialByID = function (id) {
  15233. var materials = this.getScene().materials;
  15234. var index;
  15235. for (index = 0; index < materials.length; index++) {
  15236. if (materials[index].id === id) {
  15237. this.material = materials[index];
  15238. return;
  15239. }
  15240. }
  15241. // Multi
  15242. var multiMaterials = this.getScene().multiMaterials;
  15243. for (index = 0; index < multiMaterials.length; index++) {
  15244. if (multiMaterials[index].id === id) {
  15245. this.material = multiMaterials[index];
  15246. return;
  15247. }
  15248. }
  15249. };
  15250. Mesh.prototype.getAnimatables = function () {
  15251. var results = [];
  15252. if (this.material) {
  15253. results.push(this.material);
  15254. }
  15255. if (this.skeleton) {
  15256. results.push(this.skeleton);
  15257. }
  15258. return results;
  15259. };
  15260. // Geometry
  15261. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15262. // Position
  15263. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15264. return;
  15265. }
  15266. this._resetPointsArrayCache();
  15267. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15268. var temp = [];
  15269. var index;
  15270. for (index = 0; index < data.length; index += 3) {
  15271. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15272. }
  15273. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15274. // Normals
  15275. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15276. return;
  15277. }
  15278. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15279. temp = [];
  15280. for (index = 0; index < data.length; index += 3) {
  15281. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15282. }
  15283. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15284. // flip faces?
  15285. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15286. this.flipFaces();
  15287. }
  15288. };
  15289. // Will apply current transform to mesh and reset world matrix
  15290. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15291. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15292. this.scaling.copyFromFloats(1, 1, 1);
  15293. this.position.copyFromFloats(0, 0, 0);
  15294. this.rotation.copyFromFloats(0, 0, 0);
  15295. //only if quaternion is already set
  15296. if (this.rotationQuaternion) {
  15297. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15298. }
  15299. this._worldMatrix = BABYLON.Matrix.Identity();
  15300. };
  15301. // Cache
  15302. Mesh.prototype._resetPointsArrayCache = function () {
  15303. this._positions = null;
  15304. };
  15305. Mesh.prototype._generatePointsArray = function () {
  15306. if (this._positions)
  15307. return true;
  15308. this._positions = [];
  15309. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15310. if (!data) {
  15311. return false;
  15312. }
  15313. for (var index = 0; index < data.length; index += 3) {
  15314. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15315. }
  15316. return true;
  15317. };
  15318. // Clone
  15319. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15320. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15321. };
  15322. // Dispose
  15323. Mesh.prototype.dispose = function (doNotRecurse) {
  15324. if (this._geometry) {
  15325. this._geometry.releaseForMesh(this, true);
  15326. }
  15327. // Instances
  15328. if (this._worldMatricesInstancesBuffer) {
  15329. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15330. this._worldMatricesInstancesBuffer = null;
  15331. }
  15332. while (this.instances.length) {
  15333. this.instances[0].dispose();
  15334. }
  15335. _super.prototype.dispose.call(this, doNotRecurse);
  15336. };
  15337. // Geometric tools
  15338. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15339. var _this = this;
  15340. var scene = this.getScene();
  15341. var onload = function (img) {
  15342. // Getting height map data
  15343. var canvas = document.createElement("canvas");
  15344. var context = canvas.getContext("2d");
  15345. var heightMapWidth = img.width;
  15346. var heightMapHeight = img.height;
  15347. canvas.width = heightMapWidth;
  15348. canvas.height = heightMapHeight;
  15349. context.drawImage(img, 0, 0);
  15350. // Create VertexData from map data
  15351. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15352. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15353. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15354. //execute success callback, if set
  15355. if (onSuccess) {
  15356. onSuccess(_this);
  15357. }
  15358. };
  15359. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15360. };
  15361. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15362. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15363. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15364. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15365. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15366. return;
  15367. }
  15368. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15369. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15370. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15371. var position = BABYLON.Vector3.Zero();
  15372. var normal = BABYLON.Vector3.Zero();
  15373. var uv = BABYLON.Vector2.Zero();
  15374. for (var index = 0; index < positions.length; index += 3) {
  15375. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15376. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15377. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15378. // Compute height
  15379. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15380. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15381. var pos = (u + v * heightMapWidth) * 4;
  15382. var r = buffer[pos] / 255.0;
  15383. var g = buffer[pos + 1] / 255.0;
  15384. var b = buffer[pos + 2] / 255.0;
  15385. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15386. normal.normalize();
  15387. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15388. position = position.add(normal);
  15389. position.toArray(positions, index);
  15390. }
  15391. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15392. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15393. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15394. };
  15395. Mesh.prototype.convertToFlatShadedMesh = function () {
  15396. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15397. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15398. var kinds = this.getVerticesDataKinds();
  15399. var vbs = [];
  15400. var data = [];
  15401. var newdata = [];
  15402. var updatableNormals = false;
  15403. var kindIndex;
  15404. var kind;
  15405. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15406. kind = kinds[kindIndex];
  15407. var vertexBuffer = this.getVertexBuffer(kind);
  15408. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15409. updatableNormals = vertexBuffer.isUpdatable();
  15410. kinds.splice(kindIndex, 1);
  15411. kindIndex--;
  15412. continue;
  15413. }
  15414. vbs[kind] = vertexBuffer;
  15415. data[kind] = vbs[kind].getData();
  15416. newdata[kind] = [];
  15417. }
  15418. // Save previous submeshes
  15419. var previousSubmeshes = this.subMeshes.slice(0);
  15420. var indices = this.getIndices();
  15421. var totalIndices = this.getTotalIndices();
  15422. // Generating unique vertices per face
  15423. var index;
  15424. for (index = 0; index < totalIndices; index++) {
  15425. var vertexIndex = indices[index];
  15426. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15427. kind = kinds[kindIndex];
  15428. var stride = vbs[kind].getStrideSize();
  15429. for (var offset = 0; offset < stride; offset++) {
  15430. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15431. }
  15432. }
  15433. }
  15434. // Updating faces & normal
  15435. var normals = [];
  15436. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15437. for (index = 0; index < totalIndices; index += 3) {
  15438. indices[index] = index;
  15439. indices[index + 1] = index + 1;
  15440. indices[index + 2] = index + 2;
  15441. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15442. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15443. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15444. var p1p2 = p1.subtract(p2);
  15445. var p3p2 = p3.subtract(p2);
  15446. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15447. // Store same normals for every vertex
  15448. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15449. normals.push(normal.x);
  15450. normals.push(normal.y);
  15451. normals.push(normal.z);
  15452. }
  15453. }
  15454. this.setIndices(indices);
  15455. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15456. // Updating vertex buffers
  15457. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15458. kind = kinds[kindIndex];
  15459. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15460. }
  15461. // Updating submeshes
  15462. this.releaseSubMeshes();
  15463. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15464. var previousOne = previousSubmeshes[submeshIndex];
  15465. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15466. }
  15467. this.synchronizeInstances();
  15468. };
  15469. // will inverse faces orientations, and invert normals too if specified
  15470. Mesh.prototype.flipFaces = function (flipNormals) {
  15471. if (flipNormals === void 0) { flipNormals = false; }
  15472. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15473. var i;
  15474. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15475. for (i = 0; i < vertex_data.normals.length; i++) {
  15476. vertex_data.normals[i] *= -1;
  15477. }
  15478. }
  15479. var temp;
  15480. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15481. // reassign indices
  15482. temp = vertex_data.indices[i + 1];
  15483. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15484. vertex_data.indices[i + 2] = temp;
  15485. }
  15486. vertex_data.applyToMesh(this);
  15487. };
  15488. // Instances
  15489. Mesh.prototype.createInstance = function (name) {
  15490. return new BABYLON.InstancedMesh(name, this);
  15491. };
  15492. Mesh.prototype.synchronizeInstances = function () {
  15493. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15494. var instance = this.instances[instanceIndex];
  15495. instance._syncSubMeshes();
  15496. }
  15497. };
  15498. /**
  15499. * Simplify the mesh according to the given array of settings.
  15500. * Function will return immediately and will simplify async.
  15501. * @param settings a collection of simplification settings.
  15502. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15503. * @param type the type of simplification to run.
  15504. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15505. */
  15506. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15507. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15508. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15509. this.getScene().simplificationQueue.addTask({
  15510. settings: settings,
  15511. parallelProcessing: parallelProcessing,
  15512. mesh: this,
  15513. simplificationType: simplificationType,
  15514. successCallback: successCallback
  15515. });
  15516. };
  15517. /**
  15518. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15519. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15520. * This should be used together with the simplification to avoid disappearing triangles.
  15521. * @param successCallback an optional success callback to be called after the optimization finished.
  15522. */
  15523. Mesh.prototype.optimizeIndices = function (successCallback) {
  15524. var _this = this;
  15525. var indices = this.getIndices();
  15526. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15527. var vectorPositions = [];
  15528. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15529. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15530. }
  15531. var dupes = [];
  15532. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15533. var realPos = vectorPositions.length - 1 - iteration;
  15534. var testedPosition = vectorPositions[realPos];
  15535. for (var j = 0; j < realPos; ++j) {
  15536. var againstPosition = vectorPositions[j];
  15537. if (testedPosition.equals(againstPosition)) {
  15538. dupes[realPos] = j;
  15539. break;
  15540. }
  15541. }
  15542. }, function () {
  15543. for (var i = 0; i < indices.length; ++i) {
  15544. indices[i] = dupes[indices[i]] || indices[i];
  15545. }
  15546. //indices are now reordered
  15547. var originalSubMeshes = _this.subMeshes.slice(0);
  15548. _this.setIndices(indices);
  15549. _this.subMeshes = originalSubMeshes;
  15550. if (successCallback) {
  15551. successCallback(_this);
  15552. }
  15553. });
  15554. };
  15555. // Statics
  15556. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15557. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15558. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15559. if (ribbonInstance) {
  15560. // positionFunction : ribbon case
  15561. // only pathArray and sideOrientation parameters are taken into account for positions update
  15562. var positionFunction = function (positions) {
  15563. var minlg = pathArray[0].length;
  15564. var i = 0;
  15565. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15566. for (var si = 1; si <= ns; si++) {
  15567. for (var p = 0; p < pathArray.length; p++) {
  15568. var path = pathArray[p];
  15569. var l = path.length;
  15570. minlg = (minlg < l) ? minlg : l;
  15571. var j = 0;
  15572. while (j < minlg) {
  15573. positions[i] = path[j].x;
  15574. positions[i + 1] = path[j].y;
  15575. positions[i + 2] = path[j].z;
  15576. j++;
  15577. i += 3;
  15578. }
  15579. if (ribbonInstance._closePath) {
  15580. positions[i] = path[0].x;
  15581. positions[i + 1] = path[0].y;
  15582. positions[i + 2] = path[0].z;
  15583. i += 3;
  15584. }
  15585. }
  15586. }
  15587. };
  15588. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15589. positionFunction(positions);
  15590. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15591. if (!(ribbonInstance.areNormalsFrozen)) {
  15592. var indices = ribbonInstance.getIndices();
  15593. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15594. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15595. if (ribbonInstance._closePath) {
  15596. var indexFirst = 0;
  15597. var indexLast = 0;
  15598. for (var p = 0; p < pathArray.length; p++) {
  15599. indexFirst = ribbonInstance._idx[p] * 3;
  15600. if (p + 1 < pathArray.length) {
  15601. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15602. }
  15603. else {
  15604. indexLast = normals.length - 3;
  15605. }
  15606. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15607. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15608. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15609. normals[indexLast] = normals[indexFirst];
  15610. normals[indexLast + 1] = normals[indexFirst + 1];
  15611. normals[indexLast + 2] = normals[indexFirst + 2];
  15612. }
  15613. }
  15614. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15615. }
  15616. return ribbonInstance;
  15617. }
  15618. else {
  15619. var ribbon = new Mesh(name, scene);
  15620. ribbon.sideOrientation = sideOrientation;
  15621. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15622. if (closePath) {
  15623. ribbon._idx = vertexData._idx;
  15624. }
  15625. ribbon._closePath = closePath;
  15626. vertexData.applyToMesh(ribbon, updatable);
  15627. return ribbon;
  15628. }
  15629. };
  15630. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15631. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15632. var disc = new Mesh(name, scene);
  15633. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15634. vertexData.applyToMesh(disc, updatable);
  15635. return disc;
  15636. };
  15637. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15638. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15639. // Check parameters
  15640. updatable = updatable || options.updatable;
  15641. var box = new Mesh(name, scene);
  15642. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15643. vertexData.applyToMesh(box, updatable);
  15644. return box;
  15645. };
  15646. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15647. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15648. if (diameterOrScene instanceof BABYLON.Scene) {
  15649. scene = diameterOrScene;
  15650. updatable = options.updatable;
  15651. }
  15652. else {
  15653. var segments = options;
  15654. options = {
  15655. segments: segments,
  15656. diameterX: diameterOrScene,
  15657. diameterY: diameterOrScene,
  15658. diameterZ: diameterOrScene,
  15659. sideOrientation: sideOrientation
  15660. };
  15661. }
  15662. var sphere = new Mesh(name, scene);
  15663. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15664. vertexData.applyToMesh(sphere, updatable);
  15665. return sphere;
  15666. };
  15667. // Cylinder and cone
  15668. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15669. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15670. // subdivisions is a new parameter, we need to support old signature
  15671. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15672. if (scene !== undefined) {
  15673. updatable = scene;
  15674. }
  15675. scene = subdivisions;
  15676. subdivisions = 1;
  15677. }
  15678. var cylinder = new Mesh(name, scene);
  15679. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15680. vertexData.applyToMesh(cylinder, updatable);
  15681. return cylinder;
  15682. };
  15683. // Torus (Code from SharpDX.org)
  15684. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15685. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15686. var torus = new Mesh(name, scene);
  15687. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15688. vertexData.applyToMesh(torus, updatable);
  15689. return torus;
  15690. };
  15691. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15692. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15693. var torusKnot = new Mesh(name, scene);
  15694. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15695. vertexData.applyToMesh(torusKnot, updatable);
  15696. return torusKnot;
  15697. };
  15698. // Lines
  15699. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15700. if (linesInstance === void 0) { linesInstance = null; }
  15701. if (linesInstance) {
  15702. var positionFunction = function (positions) {
  15703. var i = 0;
  15704. for (var p = 0; p < points.length; p++) {
  15705. positions[i] = points[p].x;
  15706. positions[i + 1] = points[p].y;
  15707. positions[i + 2] = points[p].z;
  15708. i += 3;
  15709. }
  15710. };
  15711. linesInstance.updateMeshPositions(positionFunction, false);
  15712. return linesInstance;
  15713. }
  15714. // lines creation
  15715. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15716. var vertexData = BABYLON.VertexData.CreateLines(points);
  15717. vertexData.applyToMesh(lines, updatable);
  15718. return lines;
  15719. };
  15720. // Dashed Lines
  15721. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15722. if (linesInstance === void 0) { linesInstance = null; }
  15723. if (linesInstance) {
  15724. var positionFunction = function (positions) {
  15725. var curvect = BABYLON.Vector3.Zero();
  15726. var nbSeg = positions.length / 6;
  15727. var lg = 0;
  15728. var nb = 0;
  15729. var shft = 0;
  15730. var dashshft = 0;
  15731. var curshft = 0;
  15732. var p = 0;
  15733. var i = 0;
  15734. var j = 0;
  15735. for (i = 0; i < points.length - 1; i++) {
  15736. points[i + 1].subtractToRef(points[i], curvect);
  15737. lg += curvect.length();
  15738. }
  15739. shft = lg / nbSeg;
  15740. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15741. for (i = 0; i < points.length - 1; i++) {
  15742. points[i + 1].subtractToRef(points[i], curvect);
  15743. nb = Math.floor(curvect.length() / shft);
  15744. curvect.normalize();
  15745. j = 0;
  15746. while (j < nb && p < positions.length) {
  15747. curshft = shft * j;
  15748. positions[p] = points[i].x + curshft * curvect.x;
  15749. positions[p + 1] = points[i].y + curshft * curvect.y;
  15750. positions[p + 2] = points[i].z + curshft * curvect.z;
  15751. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15752. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15753. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15754. p += 6;
  15755. j++;
  15756. }
  15757. }
  15758. while (p < positions.length) {
  15759. positions[p] = points[i].x;
  15760. positions[p + 1] = points[i].y;
  15761. positions[p + 2] = points[i].z;
  15762. p += 3;
  15763. }
  15764. };
  15765. linesInstance.updateMeshPositions(positionFunction, false);
  15766. return linesInstance;
  15767. }
  15768. // dashed lines creation
  15769. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15770. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15771. vertexData.applyToMesh(dashedLines, updatable);
  15772. dashedLines.dashSize = dashSize;
  15773. dashedLines.gapSize = gapSize;
  15774. return dashedLines;
  15775. };
  15776. // Extrusion
  15777. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15778. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15779. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15780. scale = scale || 1;
  15781. rotation = rotation || 0;
  15782. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15783. return extruded;
  15784. };
  15785. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15786. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15787. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15788. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15789. return extrudedCustom;
  15790. };
  15791. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15792. // extrusion geometry
  15793. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15794. var tangents = path3D.getTangents();
  15795. var normals = path3D.getNormals();
  15796. var binormals = path3D.getBinormals();
  15797. var distances = path3D.getDistances();
  15798. var angle = 0;
  15799. var returnScale = function (i, distance) { return scale; };
  15800. var returnRotation = function (i, distance) { return rotation; };
  15801. var rotate = custom ? rotateFunction : returnRotation;
  15802. var scl = custom ? scaleFunction : returnScale;
  15803. var index = 0;
  15804. for (var i = 0; i < curve.length; i++) {
  15805. var shapePath = new Array();
  15806. var angleStep = rotate(i, distances[i]);
  15807. var scaleRatio = scl(i, distances[i]);
  15808. for (var p = 0; p < shape.length; p++) {
  15809. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15810. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15811. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15812. shapePath.push(rotated);
  15813. }
  15814. shapePaths[index] = shapePath;
  15815. angle += angleStep;
  15816. index++;
  15817. }
  15818. // cap
  15819. var capPath = function (shapePath) {
  15820. var pointCap = Array();
  15821. var barycenter = BABYLON.Vector3.Zero();
  15822. var i;
  15823. for (i = 0; i < shapePath.length; i++) {
  15824. barycenter.addInPlace(shapePath[i]);
  15825. }
  15826. barycenter.scaleInPlace(1 / shapePath.length);
  15827. for (i = 0; i < shapePath.length; i++) {
  15828. pointCap.push(barycenter);
  15829. }
  15830. return pointCap;
  15831. };
  15832. switch (cap) {
  15833. case Mesh.NO_CAP:
  15834. break;
  15835. case Mesh.CAP_START:
  15836. shapePaths.unshift(capPath(shapePaths[0]));
  15837. break;
  15838. case Mesh.CAP_END:
  15839. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15840. break;
  15841. case Mesh.CAP_ALL:
  15842. shapePaths.unshift(capPath(shapePaths[0]));
  15843. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15844. break;
  15845. default:
  15846. break;
  15847. }
  15848. return shapePaths;
  15849. };
  15850. var path3D;
  15851. var pathArray;
  15852. if (instance) {
  15853. path3D = (instance.path3D).update(curve);
  15854. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15855. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15856. return instance;
  15857. }
  15858. // extruded shape creation
  15859. path3D = new BABYLON.Path3D(curve);
  15860. var newShapePaths = new Array();
  15861. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15862. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15863. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15864. extrudedGeneric.pathArray = pathArray;
  15865. extrudedGeneric.path3D = path3D;
  15866. extrudedGeneric.cap = cap;
  15867. return extrudedGeneric;
  15868. };
  15869. // Lathe
  15870. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15871. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15872. radius = radius || 1;
  15873. tessellation = tessellation || radius * 60;
  15874. var pi2 = Math.PI * 2;
  15875. var shapeLathe = new Array();
  15876. // first rotatable point
  15877. var i = 0;
  15878. while (shape[i].x === 0) {
  15879. i++;
  15880. }
  15881. var pt = shape[i];
  15882. for (i = 0; i < shape.length; i++) {
  15883. shapeLathe.push(shape[i].subtract(pt));
  15884. }
  15885. // circle path
  15886. var step = pi2 / tessellation;
  15887. var rotated;
  15888. var path = new Array();
  15889. ;
  15890. for (i = 0; i < tessellation; i++) {
  15891. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15892. path.push(rotated);
  15893. }
  15894. path.push(path[0]);
  15895. // extrusion
  15896. var scaleFunction = function () { return 1; };
  15897. var rotateFunction = function () { return 0; };
  15898. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15899. return lathe;
  15900. };
  15901. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  15902. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15903. var plane = new Mesh(name, scene);
  15904. var vertexData = BABYLON.VertexData.CreatePlane(options, sideOrientation);
  15905. vertexData.applyToMesh(plane, updatable || options.updatable);
  15906. return plane;
  15907. };
  15908. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  15909. if (heightOrScene instanceof BABYLON.Scene) {
  15910. scene = heightOrScene;
  15911. updatable = options.updatable;
  15912. }
  15913. else {
  15914. var width = options;
  15915. options = {
  15916. width: width,
  15917. height: heightOrScene,
  15918. subdivisions: subdivisions
  15919. };
  15920. }
  15921. var ground = new BABYLON.GroundMesh(name, scene);
  15922. ground._setReady(false);
  15923. ground._subdivisions = options.subdivisions || 1;
  15924. var vertexData = BABYLON.VertexData.CreateGround(options);
  15925. vertexData.applyToMesh(ground, updatable || options.updatable);
  15926. ground._setReady(true);
  15927. return ground;
  15928. };
  15929. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15930. var tiledGround = new Mesh(name, scene);
  15931. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15932. vertexData.applyToMesh(tiledGround, updatable);
  15933. return tiledGround;
  15934. };
  15935. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15936. var ground = new BABYLON.GroundMesh(name, scene);
  15937. ground._subdivisions = subdivisions;
  15938. ground._setReady(false);
  15939. var onload = function (img) {
  15940. // Getting height map data
  15941. var canvas = document.createElement("canvas");
  15942. var context = canvas.getContext("2d");
  15943. var heightMapWidth = img.width;
  15944. var heightMapHeight = img.height;
  15945. canvas.width = heightMapWidth;
  15946. canvas.height = heightMapHeight;
  15947. context.drawImage(img, 0, 0);
  15948. // Create VertexData from map data
  15949. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15950. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15951. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15952. vertexData.applyToMesh(ground, updatable);
  15953. ground._setReady(true);
  15954. //execute ready callback, if set
  15955. if (onReady) {
  15956. onReady(ground);
  15957. }
  15958. };
  15959. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15960. return ground;
  15961. };
  15962. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15963. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15964. if (tubeInstance === void 0) { tubeInstance = null; }
  15965. // tube geometry
  15966. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15967. var tangents = path3D.getTangents();
  15968. var normals = path3D.getNormals();
  15969. var distances = path3D.getDistances();
  15970. var pi2 = Math.PI * 2;
  15971. var step = pi2 / tessellation;
  15972. var returnRadius = function (i, distance) { return radius; };
  15973. var radiusFunctionFinal = radiusFunction || returnRadius;
  15974. var circlePath;
  15975. var rad;
  15976. var normal;
  15977. var rotated;
  15978. var rotationMatrix;
  15979. var index = 0;
  15980. for (var i = 0; i < path.length; i++) {
  15981. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15982. circlePath = Array(); // current circle array
  15983. normal = normals[i]; // current normal
  15984. for (var t = 0; t < tessellation; t++) {
  15985. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15986. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15987. circlePath.push(rotated);
  15988. }
  15989. circlePaths[index] = circlePath;
  15990. index++;
  15991. }
  15992. // cap
  15993. var capPath = function (nbPoints, pathIndex) {
  15994. var pointCap = Array();
  15995. for (var i = 0; i < nbPoints; i++) {
  15996. pointCap.push(path[pathIndex]);
  15997. }
  15998. return pointCap;
  15999. };
  16000. switch (cap) {
  16001. case Mesh.NO_CAP:
  16002. break;
  16003. case Mesh.CAP_START:
  16004. circlePaths.unshift(capPath(tessellation + 1, 0));
  16005. break;
  16006. case Mesh.CAP_END:
  16007. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16008. break;
  16009. case Mesh.CAP_ALL:
  16010. circlePaths.unshift(capPath(tessellation + 1, 0));
  16011. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16012. break;
  16013. default:
  16014. break;
  16015. }
  16016. return circlePaths;
  16017. };
  16018. var path3D;
  16019. var pathArray;
  16020. if (tubeInstance) {
  16021. path3D = (tubeInstance.path3D).update(path);
  16022. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  16023. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  16024. return tubeInstance;
  16025. }
  16026. // tube creation
  16027. path3D = new BABYLON.Path3D(path);
  16028. var newPathArray = new Array();
  16029. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16030. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16031. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16032. tube.pathArray = pathArray;
  16033. tube.path3D = path3D;
  16034. tube.tessellation = tessellation;
  16035. tube.cap = cap;
  16036. return tube;
  16037. };
  16038. // Decals
  16039. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16040. if (angle === void 0) { angle = 0; }
  16041. var indices = sourceMesh.getIndices();
  16042. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16043. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16044. // Getting correct rotation
  16045. if (!normal) {
  16046. var target = new BABYLON.Vector3(0, 0, 1);
  16047. var camera = sourceMesh.getScene().activeCamera;
  16048. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16049. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16050. }
  16051. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16052. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16053. var pitch = Math.atan2(normal.y, len);
  16054. // Matrix
  16055. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16056. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16057. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16058. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16059. var vertexData = new BABYLON.VertexData();
  16060. vertexData.indices = [];
  16061. vertexData.positions = [];
  16062. vertexData.normals = [];
  16063. vertexData.uvs = [];
  16064. var currentVertexDataIndex = 0;
  16065. var extractDecalVector3 = function (indexId) {
  16066. var vertexId = indices[indexId];
  16067. var result = new BABYLON.PositionNormalVertex();
  16068. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16069. // Send vector to decal local world
  16070. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16071. // Get normal
  16072. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16073. return result;
  16074. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16075. var clip = function (vertices, axis) {
  16076. if (vertices.length === 0) {
  16077. return vertices;
  16078. }
  16079. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16080. var clipVertices = function (v0, v1) {
  16081. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16082. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16083. };
  16084. var result = new Array();
  16085. for (var index = 0; index < vertices.length; index += 3) {
  16086. var v1Out;
  16087. var v2Out;
  16088. var v3Out;
  16089. var total = 0;
  16090. var nV1, nV2, nV3, nV4;
  16091. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16092. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16093. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16094. v1Out = d1 > 0;
  16095. v2Out = d2 > 0;
  16096. v3Out = d3 > 0;
  16097. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16098. switch (total) {
  16099. case 0:
  16100. result.push(vertices[index]);
  16101. result.push(vertices[index + 1]);
  16102. result.push(vertices[index + 2]);
  16103. break;
  16104. case 1:
  16105. if (v1Out) {
  16106. nV1 = vertices[index + 1];
  16107. nV2 = vertices[index + 2];
  16108. nV3 = clipVertices(vertices[index], nV1);
  16109. nV4 = clipVertices(vertices[index], nV2);
  16110. }
  16111. if (v2Out) {
  16112. nV1 = vertices[index];
  16113. nV2 = vertices[index + 2];
  16114. nV3 = clipVertices(vertices[index + 1], nV1);
  16115. nV4 = clipVertices(vertices[index + 1], nV2);
  16116. result.push(nV3);
  16117. result.push(nV2.clone());
  16118. result.push(nV1.clone());
  16119. result.push(nV2.clone());
  16120. result.push(nV3.clone());
  16121. result.push(nV4);
  16122. break;
  16123. }
  16124. if (v3Out) {
  16125. nV1 = vertices[index];
  16126. nV2 = vertices[index + 1];
  16127. nV3 = clipVertices(vertices[index + 2], nV1);
  16128. nV4 = clipVertices(vertices[index + 2], nV2);
  16129. }
  16130. result.push(nV1.clone());
  16131. result.push(nV2.clone());
  16132. result.push(nV3);
  16133. result.push(nV4);
  16134. result.push(nV3.clone());
  16135. result.push(nV2.clone());
  16136. break;
  16137. case 2:
  16138. if (!v1Out) {
  16139. nV1 = vertices[index].clone();
  16140. nV2 = clipVertices(nV1, vertices[index + 1]);
  16141. nV3 = clipVertices(nV1, vertices[index + 2]);
  16142. result.push(nV1);
  16143. result.push(nV2);
  16144. result.push(nV3);
  16145. }
  16146. if (!v2Out) {
  16147. nV1 = vertices[index + 1].clone();
  16148. nV2 = clipVertices(nV1, vertices[index + 2]);
  16149. nV3 = clipVertices(nV1, vertices[index]);
  16150. result.push(nV1);
  16151. result.push(nV2);
  16152. result.push(nV3);
  16153. }
  16154. if (!v3Out) {
  16155. nV1 = vertices[index + 2].clone();
  16156. nV2 = clipVertices(nV1, vertices[index]);
  16157. nV3 = clipVertices(nV1, vertices[index + 1]);
  16158. result.push(nV1);
  16159. result.push(nV2);
  16160. result.push(nV3);
  16161. }
  16162. break;
  16163. case 3:
  16164. break;
  16165. }
  16166. }
  16167. return result;
  16168. };
  16169. for (var index = 0; index < indices.length; index += 3) {
  16170. var faceVertices = new Array();
  16171. faceVertices.push(extractDecalVector3(index));
  16172. faceVertices.push(extractDecalVector3(index + 1));
  16173. faceVertices.push(extractDecalVector3(index + 2));
  16174. // Clip
  16175. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16176. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16177. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16178. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16179. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16180. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16181. if (faceVertices.length === 0) {
  16182. continue;
  16183. }
  16184. // Add UVs and get back to world
  16185. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16186. var vertex = faceVertices[vIndex];
  16187. vertexData.indices.push(currentVertexDataIndex);
  16188. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16189. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16190. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16191. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16192. currentVertexDataIndex++;
  16193. }
  16194. }
  16195. // Return mesh
  16196. var decal = new Mesh(name, sourceMesh.getScene());
  16197. vertexData.applyToMesh(decal);
  16198. decal.position = position.clone();
  16199. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16200. return decal;
  16201. };
  16202. // Skeletons
  16203. /**
  16204. * Update the vertex buffers by applying transformation from the bones
  16205. * @param {skeleton} skeleton to apply
  16206. */
  16207. Mesh.prototype.applySkeleton = function (skeleton) {
  16208. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16209. return this;
  16210. }
  16211. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16212. return this;
  16213. }
  16214. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16215. return this;
  16216. }
  16217. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16218. return this;
  16219. }
  16220. var source;
  16221. if (!this._sourcePositions) {
  16222. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16223. this._sourcePositions = new Float32Array(source);
  16224. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16225. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16226. }
  16227. }
  16228. if (!this._sourceNormals) {
  16229. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16230. this._sourceNormals = new Float32Array(source);
  16231. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16232. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16233. }
  16234. }
  16235. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16236. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16237. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16238. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16239. var skeletonMatrices = skeleton.getTransformMatrices();
  16240. var tempVector3 = BABYLON.Vector3.Zero();
  16241. var finalMatrix = new BABYLON.Matrix();
  16242. var tempMatrix = new BABYLON.Matrix();
  16243. for (var index = 0; index < positionsData.length; index += 3) {
  16244. var index4 = (index / 3) * 4;
  16245. var matricesWeight0 = matricesWeightsData[index4];
  16246. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16247. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16248. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16249. if (matricesWeight0 > 0) {
  16250. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16251. finalMatrix.addToSelf(tempMatrix);
  16252. }
  16253. if (matricesWeight1 > 0) {
  16254. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16255. finalMatrix.addToSelf(tempMatrix);
  16256. }
  16257. if (matricesWeight2 > 0) {
  16258. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16259. finalMatrix.addToSelf(tempMatrix);
  16260. }
  16261. if (matricesWeight3 > 0) {
  16262. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16263. finalMatrix.addToSelf(tempMatrix);
  16264. }
  16265. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16266. tempVector3.toArray(positionsData, index);
  16267. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16268. tempVector3.toArray(normalsData, index);
  16269. finalMatrix.reset();
  16270. }
  16271. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16272. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16273. return this;
  16274. };
  16275. // Tools
  16276. Mesh.MinMax = function (meshes) {
  16277. var minVector = null;
  16278. var maxVector = null;
  16279. for (var i in meshes) {
  16280. var mesh = meshes[i];
  16281. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16282. if (!minVector) {
  16283. minVector = boundingBox.minimumWorld;
  16284. maxVector = boundingBox.maximumWorld;
  16285. continue;
  16286. }
  16287. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16288. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16289. }
  16290. return {
  16291. min: minVector,
  16292. max: maxVector
  16293. };
  16294. };
  16295. Mesh.Center = function (meshesOrMinMaxVector) {
  16296. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16297. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16298. };
  16299. /**
  16300. * Merge the array of meshes into a single mesh for performance reasons.
  16301. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16302. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16303. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16304. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16305. */
  16306. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16307. if (disposeSource === void 0) { disposeSource = true; }
  16308. var index;
  16309. if (!allow32BitsIndices) {
  16310. var totalVertices = 0;
  16311. // Counting vertices
  16312. for (index = 0; index < meshes.length; index++) {
  16313. if (meshes[index]) {
  16314. totalVertices += meshes[index].getTotalVertices();
  16315. if (totalVertices > 65536) {
  16316. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16317. return null;
  16318. }
  16319. }
  16320. }
  16321. }
  16322. // Merge
  16323. var vertexData;
  16324. var otherVertexData;
  16325. var source;
  16326. for (index = 0; index < meshes.length; index++) {
  16327. if (meshes[index]) {
  16328. meshes[index].computeWorldMatrix(true);
  16329. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16330. otherVertexData.transform(meshes[index].getWorldMatrix());
  16331. if (vertexData) {
  16332. vertexData.merge(otherVertexData);
  16333. }
  16334. else {
  16335. vertexData = otherVertexData;
  16336. source = meshes[index];
  16337. }
  16338. }
  16339. }
  16340. if (!meshSubclass) {
  16341. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16342. }
  16343. vertexData.applyToMesh(meshSubclass);
  16344. // Setting properties
  16345. meshSubclass.material = source.material;
  16346. meshSubclass.checkCollisions = source.checkCollisions;
  16347. // Cleaning
  16348. if (disposeSource) {
  16349. for (index = 0; index < meshes.length; index++) {
  16350. if (meshes[index]) {
  16351. meshes[index].dispose();
  16352. }
  16353. }
  16354. }
  16355. return meshSubclass;
  16356. };
  16357. // Consts
  16358. Mesh._FRONTSIDE = 0;
  16359. Mesh._BACKSIDE = 1;
  16360. Mesh._DOUBLESIDE = 2;
  16361. Mesh._DEFAULTSIDE = 0;
  16362. Mesh._NO_CAP = 0;
  16363. Mesh._CAP_START = 1;
  16364. Mesh._CAP_END = 2;
  16365. Mesh._CAP_ALL = 3;
  16366. return Mesh;
  16367. })(BABYLON.AbstractMesh);
  16368. BABYLON.Mesh = Mesh;
  16369. })(BABYLON || (BABYLON = {}));
  16370. var BABYLON;
  16371. (function (BABYLON) {
  16372. var SubMesh = (function () {
  16373. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16374. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16375. this.materialIndex = materialIndex;
  16376. this.verticesStart = verticesStart;
  16377. this.verticesCount = verticesCount;
  16378. this.indexStart = indexStart;
  16379. this.indexCount = indexCount;
  16380. this._renderId = 0;
  16381. this._mesh = mesh;
  16382. this._renderingMesh = renderingMesh || mesh;
  16383. mesh.subMeshes.push(this);
  16384. this._trianglePlanes = [];
  16385. this._id = mesh.subMeshes.length - 1;
  16386. if (createBoundingBox) {
  16387. this.refreshBoundingInfo();
  16388. mesh.computeWorldMatrix(true);
  16389. }
  16390. }
  16391. SubMesh.prototype.getBoundingInfo = function () {
  16392. return this._boundingInfo;
  16393. };
  16394. SubMesh.prototype.getMesh = function () {
  16395. return this._mesh;
  16396. };
  16397. SubMesh.prototype.getRenderingMesh = function () {
  16398. return this._renderingMesh;
  16399. };
  16400. SubMesh.prototype.getMaterial = function () {
  16401. var rootMaterial = this._renderingMesh.material;
  16402. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16403. var multiMaterial = rootMaterial;
  16404. return multiMaterial.getSubMaterial(this.materialIndex);
  16405. }
  16406. if (!rootMaterial) {
  16407. return this._mesh.getScene().defaultMaterial;
  16408. }
  16409. return rootMaterial;
  16410. };
  16411. // Methods
  16412. SubMesh.prototype.refreshBoundingInfo = function () {
  16413. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16414. if (!data) {
  16415. this._boundingInfo = this._mesh._boundingInfo;
  16416. return;
  16417. }
  16418. var indices = this._renderingMesh.getIndices();
  16419. var extend;
  16420. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16421. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16422. }
  16423. else {
  16424. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16425. }
  16426. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16427. };
  16428. SubMesh.prototype._checkCollision = function (collider) {
  16429. return this._boundingInfo._checkCollision(collider);
  16430. };
  16431. SubMesh.prototype.updateBoundingInfo = function (world) {
  16432. if (!this._boundingInfo) {
  16433. this.refreshBoundingInfo();
  16434. }
  16435. this._boundingInfo._update(world);
  16436. };
  16437. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16438. return this._boundingInfo.isInFrustum(frustumPlanes);
  16439. };
  16440. SubMesh.prototype.render = function (enableAlphaMode) {
  16441. this._renderingMesh.render(this, enableAlphaMode);
  16442. };
  16443. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16444. if (!this._linesIndexBuffer) {
  16445. var linesIndices = [];
  16446. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16447. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16448. }
  16449. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16450. this.linesIndexCount = linesIndices.length;
  16451. }
  16452. return this._linesIndexBuffer;
  16453. };
  16454. SubMesh.prototype.canIntersects = function (ray) {
  16455. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16456. };
  16457. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16458. var intersectInfo = null;
  16459. // Triangles test
  16460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16461. var p0 = positions[indices[index]];
  16462. var p1 = positions[indices[index + 1]];
  16463. var p2 = positions[indices[index + 2]];
  16464. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16465. if (currentIntersectInfo) {
  16466. if (currentIntersectInfo.distance < 0) {
  16467. continue;
  16468. }
  16469. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16470. intersectInfo = currentIntersectInfo;
  16471. intersectInfo.faceId = index / 3;
  16472. if (fastCheck) {
  16473. break;
  16474. }
  16475. }
  16476. }
  16477. }
  16478. return intersectInfo;
  16479. };
  16480. // Clone
  16481. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16482. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16483. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16484. return result;
  16485. };
  16486. // Dispose
  16487. SubMesh.prototype.dispose = function () {
  16488. if (this._linesIndexBuffer) {
  16489. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16490. this._linesIndexBuffer = null;
  16491. }
  16492. // Remove from mesh
  16493. var index = this._mesh.subMeshes.indexOf(this);
  16494. this._mesh.subMeshes.splice(index, 1);
  16495. };
  16496. // Statics
  16497. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16498. var minVertexIndex = Number.MAX_VALUE;
  16499. var maxVertexIndex = -Number.MAX_VALUE;
  16500. renderingMesh = renderingMesh || mesh;
  16501. var indices = renderingMesh.getIndices();
  16502. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16503. var vertexIndex = indices[index];
  16504. if (vertexIndex < minVertexIndex)
  16505. minVertexIndex = vertexIndex;
  16506. if (vertexIndex > maxVertexIndex)
  16507. maxVertexIndex = vertexIndex;
  16508. }
  16509. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16510. };
  16511. return SubMesh;
  16512. })();
  16513. BABYLON.SubMesh = SubMesh;
  16514. })(BABYLON || (BABYLON = {}));
  16515. var BABYLON;
  16516. (function (BABYLON) {
  16517. var BaseTexture = (function () {
  16518. function BaseTexture(scene) {
  16519. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16520. this.hasAlpha = false;
  16521. this.getAlphaFromRGB = false;
  16522. this.level = 1;
  16523. this.isCube = false;
  16524. this.isRenderTarget = false;
  16525. this.animations = new Array();
  16526. this.coordinatesIndex = 0;
  16527. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16528. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16529. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16530. this.anisotropicFilteringLevel = 4;
  16531. this._scene = scene;
  16532. this._scene.textures.push(this);
  16533. }
  16534. BaseTexture.prototype.getScene = function () {
  16535. return this._scene;
  16536. };
  16537. BaseTexture.prototype.getTextureMatrix = function () {
  16538. return null;
  16539. };
  16540. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16541. return null;
  16542. };
  16543. BaseTexture.prototype.getInternalTexture = function () {
  16544. return this._texture;
  16545. };
  16546. BaseTexture.prototype.isReady = function () {
  16547. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16548. return true;
  16549. }
  16550. if (this._texture) {
  16551. return this._texture.isReady;
  16552. }
  16553. return false;
  16554. };
  16555. BaseTexture.prototype.getSize = function () {
  16556. if (this._texture._width) {
  16557. return { width: this._texture._width, height: this._texture._height };
  16558. }
  16559. if (this._texture._size) {
  16560. return { width: this._texture._size, height: this._texture._size };
  16561. }
  16562. return { width: 0, height: 0 };
  16563. };
  16564. BaseTexture.prototype.getBaseSize = function () {
  16565. if (!this.isReady())
  16566. return { width: 0, height: 0 };
  16567. if (this._texture._size) {
  16568. return { width: this._texture._size, height: this._texture._size };
  16569. }
  16570. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16571. };
  16572. BaseTexture.prototype.scale = function (ratio) {
  16573. };
  16574. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16575. get: function () {
  16576. return false;
  16577. },
  16578. enumerable: true,
  16579. configurable: true
  16580. });
  16581. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16582. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16583. for (var index = 0; index < texturesCache.length; index++) {
  16584. var texturesCacheEntry = texturesCache[index];
  16585. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16586. texturesCache.splice(index, 1);
  16587. return;
  16588. }
  16589. }
  16590. };
  16591. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16592. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16593. for (var index = 0; index < texturesCache.length; index++) {
  16594. var texturesCacheEntry = texturesCache[index];
  16595. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16596. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16597. texturesCacheEntry.references++;
  16598. return texturesCacheEntry;
  16599. }
  16600. }
  16601. }
  16602. return null;
  16603. };
  16604. BaseTexture.prototype.delayLoad = function () {
  16605. };
  16606. BaseTexture.prototype.releaseInternalTexture = function () {
  16607. if (!this._texture) {
  16608. return;
  16609. }
  16610. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16611. this._texture.references--;
  16612. // Final reference ?
  16613. if (this._texture.references === 0) {
  16614. var index = texturesCache.indexOf(this._texture);
  16615. texturesCache.splice(index, 1);
  16616. this._scene.getEngine()._releaseTexture(this._texture);
  16617. delete this._texture;
  16618. }
  16619. };
  16620. BaseTexture.prototype.clone = function () {
  16621. return null;
  16622. };
  16623. BaseTexture.prototype.dispose = function () {
  16624. // Remove from scene
  16625. var index = this._scene.textures.indexOf(this);
  16626. if (index >= 0) {
  16627. this._scene.textures.splice(index, 1);
  16628. }
  16629. if (this._texture === undefined) {
  16630. return;
  16631. }
  16632. this.releaseInternalTexture();
  16633. // Callback
  16634. if (this.onDispose) {
  16635. this.onDispose();
  16636. }
  16637. };
  16638. return BaseTexture;
  16639. })();
  16640. BABYLON.BaseTexture = BaseTexture;
  16641. })(BABYLON || (BABYLON = {}));
  16642. var BABYLON;
  16643. (function (BABYLON) {
  16644. var Texture = (function (_super) {
  16645. __extends(Texture, _super);
  16646. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16647. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16648. if (onLoad === void 0) { onLoad = null; }
  16649. if (onError === void 0) { onError = null; }
  16650. if (buffer === void 0) { buffer = null; }
  16651. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16652. _super.call(this, scene);
  16653. this.uOffset = 0;
  16654. this.vOffset = 0;
  16655. this.uScale = 1.0;
  16656. this.vScale = 1.0;
  16657. this.uAng = 0;
  16658. this.vAng = 0;
  16659. this.wAng = 0;
  16660. this.name = url;
  16661. this.url = url;
  16662. this._noMipmap = noMipmap;
  16663. this._invertY = invertY;
  16664. this._samplingMode = samplingMode;
  16665. this._buffer = buffer;
  16666. this._deleteBuffer = deleteBuffer;
  16667. if (!url) {
  16668. return;
  16669. }
  16670. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16671. if (!this._texture) {
  16672. if (!scene.useDelayedTextureLoading) {
  16673. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16674. if (deleteBuffer) {
  16675. delete this._buffer;
  16676. }
  16677. }
  16678. else {
  16679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16680. }
  16681. }
  16682. else {
  16683. BABYLON.Tools.SetImmediate(function () {
  16684. if (onLoad) {
  16685. onLoad();
  16686. }
  16687. });
  16688. }
  16689. }
  16690. Texture.prototype.delayLoad = function () {
  16691. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16692. return;
  16693. }
  16694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16695. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16696. if (!this._texture) {
  16697. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16698. if (this._deleteBuffer) {
  16699. delete this._buffer;
  16700. }
  16701. }
  16702. };
  16703. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16704. if (!this._texture) {
  16705. return;
  16706. }
  16707. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16708. };
  16709. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16710. x -= this.uOffset + 0.5;
  16711. y -= this.vOffset + 0.5;
  16712. z -= 0.5;
  16713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16714. t.x *= this.uScale;
  16715. t.y *= this.vScale;
  16716. t.x += 0.5;
  16717. t.y += 0.5;
  16718. t.z += 0.5;
  16719. };
  16720. Texture.prototype.getTextureMatrix = function () {
  16721. if (this.uOffset === this._cachedUOffset &&
  16722. this.vOffset === this._cachedVOffset &&
  16723. this.uScale === this._cachedUScale &&
  16724. this.vScale === this._cachedVScale &&
  16725. this.uAng === this._cachedUAng &&
  16726. this.vAng === this._cachedVAng &&
  16727. this.wAng === this._cachedWAng) {
  16728. return this._cachedTextureMatrix;
  16729. }
  16730. this._cachedUOffset = this.uOffset;
  16731. this._cachedVOffset = this.vOffset;
  16732. this._cachedUScale = this.uScale;
  16733. this._cachedVScale = this.vScale;
  16734. this._cachedUAng = this.uAng;
  16735. this._cachedVAng = this.vAng;
  16736. this._cachedWAng = this.wAng;
  16737. if (!this._cachedTextureMatrix) {
  16738. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16739. this._rowGenerationMatrix = new BABYLON.Matrix();
  16740. this._t0 = BABYLON.Vector3.Zero();
  16741. this._t1 = BABYLON.Vector3.Zero();
  16742. this._t2 = BABYLON.Vector3.Zero();
  16743. }
  16744. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16745. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16746. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16747. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16748. this._t1.subtractInPlace(this._t0);
  16749. this._t2.subtractInPlace(this._t0);
  16750. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16751. this._cachedTextureMatrix.m[0] = this._t1.x;
  16752. this._cachedTextureMatrix.m[1] = this._t1.y;
  16753. this._cachedTextureMatrix.m[2] = this._t1.z;
  16754. this._cachedTextureMatrix.m[4] = this._t2.x;
  16755. this._cachedTextureMatrix.m[5] = this._t2.y;
  16756. this._cachedTextureMatrix.m[6] = this._t2.z;
  16757. this._cachedTextureMatrix.m[8] = this._t0.x;
  16758. this._cachedTextureMatrix.m[9] = this._t0.y;
  16759. this._cachedTextureMatrix.m[10] = this._t0.z;
  16760. return this._cachedTextureMatrix;
  16761. };
  16762. Texture.prototype.getReflectionTextureMatrix = function () {
  16763. if (this.uOffset === this._cachedUOffset &&
  16764. this.vOffset === this._cachedVOffset &&
  16765. this.uScale === this._cachedUScale &&
  16766. this.vScale === this._cachedVScale &&
  16767. this.coordinatesMode === this._cachedCoordinatesMode) {
  16768. return this._cachedTextureMatrix;
  16769. }
  16770. if (!this._cachedTextureMatrix) {
  16771. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16772. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16773. }
  16774. this._cachedCoordinatesMode = this.coordinatesMode;
  16775. switch (this.coordinatesMode) {
  16776. case Texture.SPHERICAL_MODE:
  16777. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16778. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16779. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16780. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16781. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16782. break;
  16783. case Texture.PLANAR_MODE:
  16784. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16785. this._cachedTextureMatrix[0] = this.uScale;
  16786. this._cachedTextureMatrix[5] = this.vScale;
  16787. this._cachedTextureMatrix[12] = this.uOffset;
  16788. this._cachedTextureMatrix[13] = this.vOffset;
  16789. break;
  16790. case Texture.PROJECTION_MODE:
  16791. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16792. this._projectionModeMatrix.m[0] = 0.5;
  16793. this._projectionModeMatrix.m[5] = -0.5;
  16794. this._projectionModeMatrix.m[10] = 0.0;
  16795. this._projectionModeMatrix.m[12] = 0.5;
  16796. this._projectionModeMatrix.m[13] = 0.5;
  16797. this._projectionModeMatrix.m[14] = 1.0;
  16798. this._projectionModeMatrix.m[15] = 1.0;
  16799. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16800. break;
  16801. default:
  16802. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16803. break;
  16804. }
  16805. return this._cachedTextureMatrix;
  16806. };
  16807. Texture.prototype.clone = function () {
  16808. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16809. // Base texture
  16810. newTexture.hasAlpha = this.hasAlpha;
  16811. newTexture.level = this.level;
  16812. newTexture.wrapU = this.wrapU;
  16813. newTexture.wrapV = this.wrapV;
  16814. newTexture.coordinatesIndex = this.coordinatesIndex;
  16815. newTexture.coordinatesMode = this.coordinatesMode;
  16816. // Texture
  16817. newTexture.uOffset = this.uOffset;
  16818. newTexture.vOffset = this.vOffset;
  16819. newTexture.uScale = this.uScale;
  16820. newTexture.vScale = this.vScale;
  16821. newTexture.uAng = this.uAng;
  16822. newTexture.vAng = this.vAng;
  16823. newTexture.wAng = this.wAng;
  16824. return newTexture;
  16825. };
  16826. // Statics
  16827. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16828. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16829. if (onLoad === void 0) { onLoad = null; }
  16830. if (onError === void 0) { onError = null; }
  16831. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16832. };
  16833. // Constants
  16834. Texture.NEAREST_SAMPLINGMODE = 1;
  16835. Texture.BILINEAR_SAMPLINGMODE = 2;
  16836. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16837. Texture.EXPLICIT_MODE = 0;
  16838. Texture.SPHERICAL_MODE = 1;
  16839. Texture.PLANAR_MODE = 2;
  16840. Texture.CUBIC_MODE = 3;
  16841. Texture.PROJECTION_MODE = 4;
  16842. Texture.SKYBOX_MODE = 5;
  16843. Texture.CLAMP_ADDRESSMODE = 0;
  16844. Texture.WRAP_ADDRESSMODE = 1;
  16845. Texture.MIRROR_ADDRESSMODE = 2;
  16846. return Texture;
  16847. })(BABYLON.BaseTexture);
  16848. BABYLON.Texture = Texture;
  16849. })(BABYLON || (BABYLON = {}));
  16850. var BABYLON;
  16851. (function (BABYLON) {
  16852. var CubeTexture = (function (_super) {
  16853. __extends(CubeTexture, _super);
  16854. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16855. _super.call(this, scene);
  16856. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16857. this.name = rootUrl;
  16858. this.url = rootUrl;
  16859. this._noMipmap = noMipmap;
  16860. this.hasAlpha = false;
  16861. this._texture = this._getFromCache(rootUrl, noMipmap);
  16862. if (!extensions) {
  16863. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16864. }
  16865. this._extensions = extensions;
  16866. if (!this._texture) {
  16867. if (!scene.useDelayedTextureLoading) {
  16868. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16869. }
  16870. else {
  16871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16872. }
  16873. }
  16874. this.isCube = true;
  16875. this._textureMatrix = BABYLON.Matrix.Identity();
  16876. }
  16877. CubeTexture.prototype.clone = function () {
  16878. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16879. // Base texture
  16880. newTexture.level = this.level;
  16881. newTexture.wrapU = this.wrapU;
  16882. newTexture.wrapV = this.wrapV;
  16883. newTexture.coordinatesIndex = this.coordinatesIndex;
  16884. newTexture.coordinatesMode = this.coordinatesMode;
  16885. return newTexture;
  16886. };
  16887. // Methods
  16888. CubeTexture.prototype.delayLoad = function () {
  16889. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16890. return;
  16891. }
  16892. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16893. this._texture = this._getFromCache(this.url, this._noMipmap);
  16894. if (!this._texture) {
  16895. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16896. }
  16897. };
  16898. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16899. return this._textureMatrix;
  16900. };
  16901. return CubeTexture;
  16902. })(BABYLON.BaseTexture);
  16903. BABYLON.CubeTexture = CubeTexture;
  16904. })(BABYLON || (BABYLON = {}));
  16905. var BABYLON;
  16906. (function (BABYLON) {
  16907. var RenderTargetTexture = (function (_super) {
  16908. __extends(RenderTargetTexture, _super);
  16909. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16910. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16911. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16912. _super.call(this, null, scene, !generateMipMaps);
  16913. this.renderList = new Array();
  16914. this.renderParticles = true;
  16915. this.renderSprites = false;
  16916. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16917. this._currentRefreshId = -1;
  16918. this._refreshRate = 1;
  16919. this.name = name;
  16920. this.isRenderTarget = true;
  16921. this._size = size;
  16922. this._generateMipMaps = generateMipMaps;
  16923. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16924. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16925. // Rendering groups
  16926. this._renderingManager = new BABYLON.RenderingManager(scene);
  16927. }
  16928. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16929. this._currentRefreshId = -1;
  16930. };
  16931. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16932. get: function () {
  16933. return this._refreshRate;
  16934. },
  16935. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16936. set: function (value) {
  16937. this._refreshRate = value;
  16938. this.resetRefreshCounter();
  16939. },
  16940. enumerable: true,
  16941. configurable: true
  16942. });
  16943. RenderTargetTexture.prototype._shouldRender = function () {
  16944. if (this._currentRefreshId === -1) {
  16945. this._currentRefreshId = 1;
  16946. return true;
  16947. }
  16948. if (this.refreshRate === this._currentRefreshId) {
  16949. this._currentRefreshId = 1;
  16950. return true;
  16951. }
  16952. this._currentRefreshId++;
  16953. return false;
  16954. };
  16955. RenderTargetTexture.prototype.isReady = function () {
  16956. if (!this.getScene().renderTargetsEnabled) {
  16957. return false;
  16958. }
  16959. return _super.prototype.isReady.call(this);
  16960. };
  16961. RenderTargetTexture.prototype.getRenderSize = function () {
  16962. return this._size;
  16963. };
  16964. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16965. get: function () {
  16966. return true;
  16967. },
  16968. enumerable: true,
  16969. configurable: true
  16970. });
  16971. RenderTargetTexture.prototype.scale = function (ratio) {
  16972. var newSize = this._size * ratio;
  16973. this.resize(newSize, this._generateMipMaps);
  16974. };
  16975. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16976. this.releaseInternalTexture();
  16977. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16978. };
  16979. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16980. var scene = this.getScene();
  16981. var engine = scene.getEngine();
  16982. if (this._waitingRenderList) {
  16983. this.renderList = [];
  16984. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16985. var id = this._waitingRenderList[index];
  16986. this.renderList.push(scene.getMeshByID(id));
  16987. }
  16988. delete this._waitingRenderList;
  16989. }
  16990. if (this.renderList && this.renderList.length === 0) {
  16991. return;
  16992. }
  16993. // Bind
  16994. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16995. engine.bindFramebuffer(this._texture);
  16996. }
  16997. this._renderingManager.reset();
  16998. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16999. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17000. var mesh = currentRenderList[meshIndex];
  17001. if (mesh) {
  17002. if (!mesh.isReady()) {
  17003. // Reset _currentRefreshId
  17004. this.resetRefreshCounter();
  17005. continue;
  17006. }
  17007. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17008. mesh._activate(scene.getRenderId());
  17009. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17010. var subMesh = mesh.subMeshes[subIndex];
  17011. scene._activeIndices += subMesh.indexCount;
  17012. this._renderingManager.dispatch(subMesh);
  17013. }
  17014. }
  17015. }
  17016. }
  17017. if (this.onBeforeRender) {
  17018. this.onBeforeRender();
  17019. }
  17020. // Clear
  17021. if (this.onClear) {
  17022. this.onClear(engine);
  17023. }
  17024. else {
  17025. engine.clear(scene.clearColor, true, true);
  17026. }
  17027. if (!this._doNotChangeAspectRatio) {
  17028. scene.updateTransformMatrix(true);
  17029. }
  17030. // Render
  17031. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17032. if (useCameraPostProcess) {
  17033. scene.postProcessManager._finalizeFrame(false, this._texture);
  17034. }
  17035. if (!this._doNotChangeAspectRatio) {
  17036. scene.updateTransformMatrix(true);
  17037. }
  17038. if (this.onAfterRender) {
  17039. this.onAfterRender();
  17040. }
  17041. // Dump ?
  17042. if (dumpForDebug) {
  17043. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17044. }
  17045. // Unbind
  17046. engine.unBindFramebuffer(this._texture);
  17047. if (this.onAfterUnbind) {
  17048. this.onAfterUnbind();
  17049. }
  17050. };
  17051. RenderTargetTexture.prototype.clone = function () {
  17052. var textureSize = this.getSize();
  17053. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17054. // Base texture
  17055. newTexture.hasAlpha = this.hasAlpha;
  17056. newTexture.level = this.level;
  17057. // RenderTarget Texture
  17058. newTexture.coordinatesMode = this.coordinatesMode;
  17059. newTexture.renderList = this.renderList.slice(0);
  17060. return newTexture;
  17061. };
  17062. return RenderTargetTexture;
  17063. })(BABYLON.Texture);
  17064. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17065. })(BABYLON || (BABYLON = {}));
  17066. var BABYLON;
  17067. (function (BABYLON) {
  17068. var ProceduralTexture = (function (_super) {
  17069. __extends(ProceduralTexture, _super);
  17070. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17072. _super.call(this, null, scene, !generateMipMaps);
  17073. this.isEnabled = true;
  17074. this._currentRefreshId = -1;
  17075. this._refreshRate = 1;
  17076. this._vertexDeclaration = [2];
  17077. this._vertexStrideSize = 2 * 4;
  17078. this._uniforms = new Array();
  17079. this._samplers = new Array();
  17080. this._textures = new Array();
  17081. this._floats = new Array();
  17082. this._floatsArrays = {};
  17083. this._colors3 = new Array();
  17084. this._colors4 = new Array();
  17085. this._vectors2 = new Array();
  17086. this._vectors3 = new Array();
  17087. this._matrices = new Array();
  17088. this._fallbackTextureUsed = false;
  17089. scene._proceduralTextures.push(this);
  17090. this.name = name;
  17091. this.isRenderTarget = true;
  17092. this._size = size;
  17093. this._generateMipMaps = generateMipMaps;
  17094. this.setFragment(fragment);
  17095. this._fallbackTexture = fallbackTexture;
  17096. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17097. // VBO
  17098. var vertices = [];
  17099. vertices.push(1, 1);
  17100. vertices.push(-1, 1);
  17101. vertices.push(-1, -1);
  17102. vertices.push(1, -1);
  17103. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17104. // Indices
  17105. var indices = [];
  17106. indices.push(0);
  17107. indices.push(1);
  17108. indices.push(2);
  17109. indices.push(0);
  17110. indices.push(2);
  17111. indices.push(3);
  17112. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17113. }
  17114. ProceduralTexture.prototype.reset = function () {
  17115. if (this._effect === undefined) {
  17116. return;
  17117. }
  17118. var engine = this.getScene().getEngine();
  17119. engine._releaseEffect(this._effect);
  17120. };
  17121. ProceduralTexture.prototype.isReady = function () {
  17122. var _this = this;
  17123. var engine = this.getScene().getEngine();
  17124. var shaders;
  17125. if (!this._fragment) {
  17126. return false;
  17127. }
  17128. if (this._fallbackTextureUsed) {
  17129. return true;
  17130. }
  17131. if (this._fragment.fragmentElement !== undefined) {
  17132. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17133. }
  17134. else {
  17135. shaders = { vertex: "procedural", fragment: this._fragment };
  17136. }
  17137. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17138. _this.releaseInternalTexture();
  17139. if (_this._fallbackTexture) {
  17140. _this._texture = _this._fallbackTexture._texture;
  17141. _this._texture.references++;
  17142. }
  17143. _this._fallbackTextureUsed = true;
  17144. });
  17145. return this._effect.isReady();
  17146. };
  17147. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17148. this._currentRefreshId = -1;
  17149. };
  17150. ProceduralTexture.prototype.setFragment = function (fragment) {
  17151. this._fragment = fragment;
  17152. };
  17153. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17154. get: function () {
  17155. return this._refreshRate;
  17156. },
  17157. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17158. set: function (value) {
  17159. this._refreshRate = value;
  17160. this.resetRefreshCounter();
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. ProceduralTexture.prototype._shouldRender = function () {
  17166. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17167. return false;
  17168. }
  17169. if (this._fallbackTextureUsed) {
  17170. return false;
  17171. }
  17172. if (this._currentRefreshId === -1) {
  17173. this._currentRefreshId = 1;
  17174. return true;
  17175. }
  17176. if (this.refreshRate === this._currentRefreshId) {
  17177. this._currentRefreshId = 1;
  17178. return true;
  17179. }
  17180. this._currentRefreshId++;
  17181. return false;
  17182. };
  17183. ProceduralTexture.prototype.getRenderSize = function () {
  17184. return this._size;
  17185. };
  17186. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17187. if (this._fallbackTextureUsed) {
  17188. return;
  17189. }
  17190. this.releaseInternalTexture();
  17191. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17192. };
  17193. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17194. if (this._uniforms.indexOf(uniformName) === -1) {
  17195. this._uniforms.push(uniformName);
  17196. }
  17197. };
  17198. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17199. if (this._samplers.indexOf(name) === -1) {
  17200. this._samplers.push(name);
  17201. }
  17202. this._textures[name] = texture;
  17203. return this;
  17204. };
  17205. ProceduralTexture.prototype.setFloat = function (name, value) {
  17206. this._checkUniform(name);
  17207. this._floats[name] = value;
  17208. return this;
  17209. };
  17210. ProceduralTexture.prototype.setFloats = function (name, value) {
  17211. this._checkUniform(name);
  17212. this._floatsArrays[name] = value;
  17213. return this;
  17214. };
  17215. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17216. this._checkUniform(name);
  17217. this._colors3[name] = value;
  17218. return this;
  17219. };
  17220. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17221. this._checkUniform(name);
  17222. this._colors4[name] = value;
  17223. return this;
  17224. };
  17225. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17226. this._checkUniform(name);
  17227. this._vectors2[name] = value;
  17228. return this;
  17229. };
  17230. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17231. this._checkUniform(name);
  17232. this._vectors3[name] = value;
  17233. return this;
  17234. };
  17235. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17236. this._checkUniform(name);
  17237. this._matrices[name] = value;
  17238. return this;
  17239. };
  17240. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17241. var scene = this.getScene();
  17242. var engine = scene.getEngine();
  17243. engine.bindFramebuffer(this._texture);
  17244. // Clear
  17245. engine.clear(scene.clearColor, true, true);
  17246. // Render
  17247. engine.enableEffect(this._effect);
  17248. engine.setState(false);
  17249. // Texture
  17250. for (var name in this._textures) {
  17251. this._effect.setTexture(name, this._textures[name]);
  17252. }
  17253. // Float
  17254. for (name in this._floats) {
  17255. this._effect.setFloat(name, this._floats[name]);
  17256. }
  17257. // Floats
  17258. for (name in this._floatsArrays) {
  17259. this._effect.setArray(name, this._floatsArrays[name]);
  17260. }
  17261. // Color3
  17262. for (name in this._colors3) {
  17263. this._effect.setColor3(name, this._colors3[name]);
  17264. }
  17265. // Color4
  17266. for (name in this._colors4) {
  17267. var color = this._colors4[name];
  17268. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17269. }
  17270. // Vector2
  17271. for (name in this._vectors2) {
  17272. this._effect.setVector2(name, this._vectors2[name]);
  17273. }
  17274. // Vector3
  17275. for (name in this._vectors3) {
  17276. this._effect.setVector3(name, this._vectors3[name]);
  17277. }
  17278. // Matrix
  17279. for (name in this._matrices) {
  17280. this._effect.setMatrix(name, this._matrices[name]);
  17281. }
  17282. // VBOs
  17283. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17284. // Draw order
  17285. engine.draw(true, 0, 6);
  17286. // Unbind
  17287. engine.unBindFramebuffer(this._texture);
  17288. };
  17289. ProceduralTexture.prototype.clone = function () {
  17290. var textureSize = this.getSize();
  17291. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17292. // Base texture
  17293. newTexture.hasAlpha = this.hasAlpha;
  17294. newTexture.level = this.level;
  17295. // RenderTarget Texture
  17296. newTexture.coordinatesMode = this.coordinatesMode;
  17297. return newTexture;
  17298. };
  17299. ProceduralTexture.prototype.dispose = function () {
  17300. var index = this.getScene()._proceduralTextures.indexOf(this);
  17301. if (index >= 0) {
  17302. this.getScene()._proceduralTextures.splice(index, 1);
  17303. }
  17304. _super.prototype.dispose.call(this);
  17305. };
  17306. return ProceduralTexture;
  17307. })(BABYLON.Texture);
  17308. BABYLON.ProceduralTexture = ProceduralTexture;
  17309. })(BABYLON || (BABYLON = {}));
  17310. var BABYLON;
  17311. (function (BABYLON) {
  17312. var MirrorTexture = (function (_super) {
  17313. __extends(MirrorTexture, _super);
  17314. function MirrorTexture(name, size, scene, generateMipMaps) {
  17315. var _this = this;
  17316. _super.call(this, name, size, scene, generateMipMaps, true);
  17317. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17318. this._transformMatrix = BABYLON.Matrix.Zero();
  17319. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17320. this.onBeforeRender = function () {
  17321. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17322. _this._savedViewMatrix = scene.getViewMatrix();
  17323. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17324. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17325. scene.clipPlane = _this.mirrorPlane;
  17326. scene.getEngine().cullBackFaces = false;
  17327. };
  17328. this.onAfterRender = function () {
  17329. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17330. scene.getEngine().cullBackFaces = true;
  17331. delete scene.clipPlane;
  17332. };
  17333. }
  17334. MirrorTexture.prototype.clone = function () {
  17335. var textureSize = this.getSize();
  17336. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17337. // Base texture
  17338. newTexture.hasAlpha = this.hasAlpha;
  17339. newTexture.level = this.level;
  17340. // Mirror Texture
  17341. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17342. newTexture.renderList = this.renderList.slice(0);
  17343. return newTexture;
  17344. };
  17345. return MirrorTexture;
  17346. })(BABYLON.RenderTargetTexture);
  17347. BABYLON.MirrorTexture = MirrorTexture;
  17348. })(BABYLON || (BABYLON = {}));
  17349. var BABYLON;
  17350. (function (BABYLON) {
  17351. var DynamicTexture = (function (_super) {
  17352. __extends(DynamicTexture, _super);
  17353. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17355. _super.call(this, null, scene, !generateMipMaps);
  17356. this.name = name;
  17357. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17358. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17359. this._generateMipMaps = generateMipMaps;
  17360. if (options.getContext) {
  17361. this._canvas = options;
  17362. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17363. }
  17364. else {
  17365. this._canvas = document.createElement("canvas");
  17366. if (options.width) {
  17367. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17368. }
  17369. else {
  17370. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17371. }
  17372. }
  17373. var textureSize = this.getSize();
  17374. this._canvas.width = textureSize.width;
  17375. this._canvas.height = textureSize.height;
  17376. this._context = this._canvas.getContext("2d");
  17377. }
  17378. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17379. get: function () {
  17380. return true;
  17381. },
  17382. enumerable: true,
  17383. configurable: true
  17384. });
  17385. DynamicTexture.prototype.scale = function (ratio) {
  17386. var textureSize = this.getSize();
  17387. textureSize.width *= ratio;
  17388. textureSize.height *= ratio;
  17389. this._canvas.width = textureSize.width;
  17390. this._canvas.height = textureSize.height;
  17391. this.releaseInternalTexture();
  17392. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17393. };
  17394. DynamicTexture.prototype.getContext = function () {
  17395. return this._context;
  17396. };
  17397. DynamicTexture.prototype.clear = function () {
  17398. var size = this.getSize();
  17399. this._context.fillRect(0, 0, size.width, size.height);
  17400. };
  17401. DynamicTexture.prototype.update = function (invertY) {
  17402. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17403. };
  17404. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17405. if (update === void 0) { update = true; }
  17406. var size = this.getSize();
  17407. if (clearColor) {
  17408. this._context.fillStyle = clearColor;
  17409. this._context.fillRect(0, 0, size.width, size.height);
  17410. }
  17411. this._context.font = font;
  17412. if (x === null) {
  17413. var textSize = this._context.measureText(text);
  17414. x = (size.width - textSize.width) / 2;
  17415. }
  17416. this._context.fillStyle = color;
  17417. this._context.fillText(text, x, y);
  17418. if (update) {
  17419. this.update(invertY);
  17420. }
  17421. };
  17422. DynamicTexture.prototype.clone = function () {
  17423. var textureSize = this.getSize();
  17424. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17425. // Base texture
  17426. newTexture.hasAlpha = this.hasAlpha;
  17427. newTexture.level = this.level;
  17428. // Dynamic Texture
  17429. newTexture.wrapU = this.wrapU;
  17430. newTexture.wrapV = this.wrapV;
  17431. return newTexture;
  17432. };
  17433. return DynamicTexture;
  17434. })(BABYLON.Texture);
  17435. BABYLON.DynamicTexture = DynamicTexture;
  17436. })(BABYLON || (BABYLON = {}));
  17437. var BABYLON;
  17438. (function (BABYLON) {
  17439. var VideoTexture = (function (_super) {
  17440. __extends(VideoTexture, _super);
  17441. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17442. var _this = this;
  17443. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17444. if (invertY === void 0) { invertY = false; }
  17445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17446. _super.call(this, null, scene, !generateMipMaps, invertY);
  17447. this._autoLaunch = true;
  17448. this.name = name;
  17449. this.video = document.createElement("video");
  17450. this.video.autoplay = false;
  17451. this.video.loop = true;
  17452. this.video.addEventListener("canplaythrough", function () {
  17453. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17454. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17455. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17456. }
  17457. else {
  17458. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17459. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17460. generateMipMaps = false;
  17461. }
  17462. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17463. _this._texture.isReady = true;
  17464. });
  17465. urls.forEach(function (url) {
  17466. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17467. var source = document.createElement("source");
  17468. source.src = url;
  17469. _this.video.appendChild(source);
  17470. });
  17471. this._lastUpdate = BABYLON.Tools.Now;
  17472. }
  17473. VideoTexture.prototype.update = function () {
  17474. if (this._autoLaunch) {
  17475. this._autoLaunch = false;
  17476. this.video.play();
  17477. }
  17478. var now = BABYLON.Tools.Now;
  17479. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17480. return false;
  17481. }
  17482. this._lastUpdate = now;
  17483. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17484. return true;
  17485. };
  17486. return VideoTexture;
  17487. })(BABYLON.Texture);
  17488. BABYLON.VideoTexture = VideoTexture;
  17489. })(BABYLON || (BABYLON = {}));
  17490. var BABYLON;
  17491. (function (BABYLON) {
  17492. var CustomProceduralTexture = (function (_super) {
  17493. __extends(CustomProceduralTexture, _super);
  17494. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17495. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17496. this._animate = true;
  17497. this._time = 0;
  17498. this._texturePath = texturePath;
  17499. //Try to load json
  17500. this.loadJson(texturePath);
  17501. this.refreshRate = 1;
  17502. }
  17503. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17504. var _this = this;
  17505. var that = this;
  17506. function noConfigFile() {
  17507. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17508. try {
  17509. that.setFragment(that._texturePath);
  17510. }
  17511. catch (ex) {
  17512. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17513. }
  17514. }
  17515. var configFileUrl = jsonUrl + "/config.json";
  17516. var xhr = new XMLHttpRequest();
  17517. xhr.open("GET", configFileUrl, true);
  17518. xhr.addEventListener("load", function () {
  17519. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17520. try {
  17521. _this._config = JSON.parse(xhr.response);
  17522. _this.updateShaderUniforms();
  17523. _this.updateTextures();
  17524. _this.setFragment(_this._texturePath + "/custom");
  17525. _this._animate = _this._config.animate;
  17526. _this.refreshRate = _this._config.refreshrate;
  17527. }
  17528. catch (ex) {
  17529. noConfigFile();
  17530. }
  17531. }
  17532. else {
  17533. noConfigFile();
  17534. }
  17535. }, false);
  17536. xhr.addEventListener("error", function () {
  17537. noConfigFile();
  17538. }, false);
  17539. try {
  17540. xhr.send();
  17541. }
  17542. catch (ex) {
  17543. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17544. }
  17545. };
  17546. CustomProceduralTexture.prototype.isReady = function () {
  17547. if (!_super.prototype.isReady.call(this)) {
  17548. return false;
  17549. }
  17550. for (var name in this._textures) {
  17551. var texture = this._textures[name];
  17552. if (!texture.isReady()) {
  17553. return false;
  17554. }
  17555. }
  17556. return true;
  17557. };
  17558. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17559. if (this._animate) {
  17560. this._time += this.getScene().getAnimationRatio() * 0.03;
  17561. this.updateShaderUniforms();
  17562. }
  17563. _super.prototype.render.call(this, useCameraPostProcess);
  17564. };
  17565. CustomProceduralTexture.prototype.updateTextures = function () {
  17566. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17567. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17568. }
  17569. };
  17570. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17571. if (this._config) {
  17572. for (var j = 0; j < this._config.uniforms.length; j++) {
  17573. var uniform = this._config.uniforms[j];
  17574. switch (uniform.type) {
  17575. case "float":
  17576. this.setFloat(uniform.name, uniform.value);
  17577. break;
  17578. case "color3":
  17579. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17580. break;
  17581. case "color4":
  17582. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17583. break;
  17584. case "vector2":
  17585. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17586. break;
  17587. case "vector3":
  17588. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17589. break;
  17590. }
  17591. }
  17592. }
  17593. this.setFloat("time", this._time);
  17594. };
  17595. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17596. get: function () {
  17597. return this._animate;
  17598. },
  17599. set: function (value) {
  17600. this._animate = value;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. return CustomProceduralTexture;
  17606. })(BABYLON.ProceduralTexture);
  17607. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17608. })(BABYLON || (BABYLON = {}));
  17609. var BABYLON;
  17610. (function (BABYLON) {
  17611. var WoodProceduralTexture = (function (_super) {
  17612. __extends(WoodProceduralTexture, _super);
  17613. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17614. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17615. this._ampScale = 100.0;
  17616. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17617. this.updateShaderUniforms();
  17618. this.refreshRate = 0;
  17619. }
  17620. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17621. this.setFloat("ampScale", this._ampScale);
  17622. this.setColor3("woodColor", this._woodColor);
  17623. };
  17624. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17625. get: function () {
  17626. return this._ampScale;
  17627. },
  17628. set: function (value) {
  17629. this._ampScale = value;
  17630. this.updateShaderUniforms();
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17636. get: function () {
  17637. return this._woodColor;
  17638. },
  17639. set: function (value) {
  17640. this._woodColor = value;
  17641. this.updateShaderUniforms();
  17642. },
  17643. enumerable: true,
  17644. configurable: true
  17645. });
  17646. return WoodProceduralTexture;
  17647. })(BABYLON.ProceduralTexture);
  17648. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17649. var FireProceduralTexture = (function (_super) {
  17650. __extends(FireProceduralTexture, _super);
  17651. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17652. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17653. this._time = 0.0;
  17654. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17655. this._autoGenerateTime = true;
  17656. this._alphaThreshold = 0.5;
  17657. this._fireColors = FireProceduralTexture.RedFireColors;
  17658. this.updateShaderUniforms();
  17659. this.refreshRate = 1;
  17660. }
  17661. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17662. this.setFloat("time", this._time);
  17663. this.setVector2("speed", this._speed);
  17664. this.setColor3("c1", this._fireColors[0]);
  17665. this.setColor3("c2", this._fireColors[1]);
  17666. this.setColor3("c3", this._fireColors[2]);
  17667. this.setColor3("c4", this._fireColors[3]);
  17668. this.setColor3("c5", this._fireColors[4]);
  17669. this.setColor3("c6", this._fireColors[5]);
  17670. this.setFloat("alphaThreshold", this._alphaThreshold);
  17671. };
  17672. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17673. if (this._autoGenerateTime) {
  17674. this._time += this.getScene().getAnimationRatio() * 0.03;
  17675. this.updateShaderUniforms();
  17676. }
  17677. _super.prototype.render.call(this, useCameraPostProcess);
  17678. };
  17679. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17680. get: function () {
  17681. return [
  17682. new BABYLON.Color3(0.5, 0.0, 1.0),
  17683. new BABYLON.Color3(0.9, 0.0, 1.0),
  17684. new BABYLON.Color3(0.2, 0.0, 1.0),
  17685. new BABYLON.Color3(1.0, 0.9, 1.0),
  17686. new BABYLON.Color3(0.1, 0.1, 1.0),
  17687. new BABYLON.Color3(0.9, 0.9, 1.0)
  17688. ];
  17689. },
  17690. enumerable: true,
  17691. configurable: true
  17692. });
  17693. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17694. get: function () {
  17695. return [
  17696. new BABYLON.Color3(0.5, 1.0, 0.0),
  17697. new BABYLON.Color3(0.5, 1.0, 0.0),
  17698. new BABYLON.Color3(0.3, 0.4, 0.0),
  17699. new BABYLON.Color3(0.5, 1.0, 0.0),
  17700. new BABYLON.Color3(0.2, 0.0, 0.0),
  17701. new BABYLON.Color3(0.5, 1.0, 0.0)
  17702. ];
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17708. get: function () {
  17709. return [
  17710. new BABYLON.Color3(0.5, 0.0, 0.1),
  17711. new BABYLON.Color3(0.9, 0.0, 0.0),
  17712. new BABYLON.Color3(0.2, 0.0, 0.0),
  17713. new BABYLON.Color3(1.0, 0.9, 0.0),
  17714. new BABYLON.Color3(0.1, 0.1, 0.1),
  17715. new BABYLON.Color3(0.9, 0.9, 0.9)
  17716. ];
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17722. get: function () {
  17723. return [
  17724. new BABYLON.Color3(0.1, 0.0, 0.5),
  17725. new BABYLON.Color3(0.0, 0.0, 0.5),
  17726. new BABYLON.Color3(0.1, 0.0, 0.2),
  17727. new BABYLON.Color3(0.0, 0.0, 1.0),
  17728. new BABYLON.Color3(0.1, 0.2, 0.3),
  17729. new BABYLON.Color3(0.0, 0.2, 0.9)
  17730. ];
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17736. get: function () {
  17737. return this._fireColors;
  17738. },
  17739. set: function (value) {
  17740. this._fireColors = value;
  17741. this.updateShaderUniforms();
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17747. get: function () {
  17748. return this._time;
  17749. },
  17750. set: function (value) {
  17751. this._time = value;
  17752. this.updateShaderUniforms();
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17758. get: function () {
  17759. return this._speed;
  17760. },
  17761. set: function (value) {
  17762. this._speed = value;
  17763. this.updateShaderUniforms();
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17769. get: function () {
  17770. return this._alphaThreshold;
  17771. },
  17772. set: function (value) {
  17773. this._alphaThreshold = value;
  17774. this.updateShaderUniforms();
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. return FireProceduralTexture;
  17780. })(BABYLON.ProceduralTexture);
  17781. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17782. var CloudProceduralTexture = (function (_super) {
  17783. __extends(CloudProceduralTexture, _super);
  17784. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17785. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17786. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17787. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17788. this.updateShaderUniforms();
  17789. this.refreshRate = 0;
  17790. }
  17791. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17792. this.setColor4("skyColor", this._skyColor);
  17793. this.setColor4("cloudColor", this._cloudColor);
  17794. };
  17795. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17796. get: function () {
  17797. return this._skyColor;
  17798. },
  17799. set: function (value) {
  17800. this._skyColor = value;
  17801. this.updateShaderUniforms();
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17807. get: function () {
  17808. return this._cloudColor;
  17809. },
  17810. set: function (value) {
  17811. this._cloudColor = value;
  17812. this.updateShaderUniforms();
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. return CloudProceduralTexture;
  17818. })(BABYLON.ProceduralTexture);
  17819. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17820. var GrassProceduralTexture = (function (_super) {
  17821. __extends(GrassProceduralTexture, _super);
  17822. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17823. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17824. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17825. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17826. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17827. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17828. this._grassColors = [
  17829. new BABYLON.Color3(0.29, 0.38, 0.02),
  17830. new BABYLON.Color3(0.36, 0.49, 0.09),
  17831. new BABYLON.Color3(0.51, 0.6, 0.28)
  17832. ];
  17833. this.updateShaderUniforms();
  17834. this.refreshRate = 0;
  17835. }
  17836. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17837. this.setColor3("herb1Color", this._grassColors[0]);
  17838. this.setColor3("herb2Color", this._grassColors[1]);
  17839. this.setColor3("herb3Color", this._grassColors[2]);
  17840. this.setColor3("groundColor", this._groundColor);
  17841. };
  17842. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17843. get: function () {
  17844. return this._grassColors;
  17845. },
  17846. set: function (value) {
  17847. this._grassColors = value;
  17848. this.updateShaderUniforms();
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17854. get: function () {
  17855. return this._groundColor;
  17856. },
  17857. set: function (value) {
  17858. this.groundColor = value;
  17859. this.updateShaderUniforms();
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. return GrassProceduralTexture;
  17865. })(BABYLON.ProceduralTexture);
  17866. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17867. var RoadProceduralTexture = (function (_super) {
  17868. __extends(RoadProceduralTexture, _super);
  17869. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17870. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17871. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17872. this.updateShaderUniforms();
  17873. this.refreshRate = 0;
  17874. }
  17875. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17876. this.setColor3("roadColor", this._roadColor);
  17877. };
  17878. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17879. get: function () {
  17880. return this._roadColor;
  17881. },
  17882. set: function (value) {
  17883. this._roadColor = value;
  17884. this.updateShaderUniforms();
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. return RoadProceduralTexture;
  17890. })(BABYLON.ProceduralTexture);
  17891. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17892. var BrickProceduralTexture = (function (_super) {
  17893. __extends(BrickProceduralTexture, _super);
  17894. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17895. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17896. this._numberOfBricksHeight = 15;
  17897. this._numberOfBricksWidth = 5;
  17898. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17899. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17900. this.updateShaderUniforms();
  17901. this.refreshRate = 0;
  17902. }
  17903. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17904. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17905. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17906. this.setColor3("brickColor", this._brickColor);
  17907. this.setColor3("jointColor", this._jointColor);
  17908. };
  17909. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17910. get: function () {
  17911. return this._numberOfBricksHeight;
  17912. },
  17913. set: function (value) {
  17914. this._numberOfBricksHeight = value;
  17915. this.updateShaderUniforms();
  17916. },
  17917. enumerable: true,
  17918. configurable: true
  17919. });
  17920. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17921. get: function () {
  17922. return this._numberOfBricksWidth;
  17923. },
  17924. set: function (value) {
  17925. this._numberOfBricksWidth = value;
  17926. this.updateShaderUniforms();
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17932. get: function () {
  17933. return this._jointColor;
  17934. },
  17935. set: function (value) {
  17936. this._jointColor = value;
  17937. this.updateShaderUniforms();
  17938. },
  17939. enumerable: true,
  17940. configurable: true
  17941. });
  17942. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17943. get: function () {
  17944. return this._brickColor;
  17945. },
  17946. set: function (value) {
  17947. this._brickColor = value;
  17948. this.updateShaderUniforms();
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. return BrickProceduralTexture;
  17954. })(BABYLON.ProceduralTexture);
  17955. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17956. var MarbleProceduralTexture = (function (_super) {
  17957. __extends(MarbleProceduralTexture, _super);
  17958. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17959. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17960. this._numberOfTilesHeight = 3;
  17961. this._numberOfTilesWidth = 3;
  17962. this._amplitude = 9.0;
  17963. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17964. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17965. this.updateShaderUniforms();
  17966. this.refreshRate = 0;
  17967. }
  17968. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17969. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17970. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17971. this.setFloat("amplitude", this._amplitude);
  17972. this.setColor3("marbleColor", this._marbleColor);
  17973. this.setColor3("jointColor", this._jointColor);
  17974. };
  17975. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17976. get: function () {
  17977. return this._numberOfTilesHeight;
  17978. },
  17979. set: function (value) {
  17980. this._numberOfTilesHeight = value;
  17981. this.updateShaderUniforms();
  17982. },
  17983. enumerable: true,
  17984. configurable: true
  17985. });
  17986. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17987. get: function () {
  17988. return this._numberOfTilesWidth;
  17989. },
  17990. set: function (value) {
  17991. this._numberOfTilesWidth = value;
  17992. this.updateShaderUniforms();
  17993. },
  17994. enumerable: true,
  17995. configurable: true
  17996. });
  17997. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17998. get: function () {
  17999. return this._jointColor;
  18000. },
  18001. set: function (value) {
  18002. this._jointColor = value;
  18003. this.updateShaderUniforms();
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18009. get: function () {
  18010. return this._marbleColor;
  18011. },
  18012. set: function (value) {
  18013. this._marbleColor = value;
  18014. this.updateShaderUniforms();
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. return MarbleProceduralTexture;
  18020. })(BABYLON.ProceduralTexture);
  18021. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18022. })(BABYLON || (BABYLON = {}));
  18023. var BABYLON;
  18024. (function (BABYLON) {
  18025. var EffectFallbacks = (function () {
  18026. function EffectFallbacks() {
  18027. this._defines = {};
  18028. this._currentRank = 32;
  18029. this._maxRank = -1;
  18030. }
  18031. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18032. if (!this._defines[rank]) {
  18033. if (rank < this._currentRank) {
  18034. this._currentRank = rank;
  18035. }
  18036. if (rank > this._maxRank) {
  18037. this._maxRank = rank;
  18038. }
  18039. this._defines[rank] = new Array();
  18040. }
  18041. this._defines[rank].push(define);
  18042. };
  18043. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18044. get: function () {
  18045. return this._currentRank <= this._maxRank;
  18046. },
  18047. enumerable: true,
  18048. configurable: true
  18049. });
  18050. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18051. var currentFallbacks = this._defines[this._currentRank];
  18052. for (var index = 0; index < currentFallbacks.length; index++) {
  18053. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18054. }
  18055. this._currentRank++;
  18056. return currentDefines;
  18057. };
  18058. return EffectFallbacks;
  18059. })();
  18060. BABYLON.EffectFallbacks = EffectFallbacks;
  18061. var Effect = (function () {
  18062. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18063. var _this = this;
  18064. this._isReady = false;
  18065. this._compilationError = "";
  18066. this._valueCache = [];
  18067. this._engine = engine;
  18068. this.name = baseName;
  18069. this.defines = defines;
  18070. this._uniformsNames = uniformsNames.concat(samplers);
  18071. this._samplers = samplers;
  18072. this._attributesNames = attributesNames;
  18073. this.onError = onError;
  18074. this.onCompiled = onCompiled;
  18075. var vertexSource;
  18076. var fragmentSource;
  18077. if (baseName.vertexElement) {
  18078. vertexSource = document.getElementById(baseName.vertexElement);
  18079. if (!vertexSource) {
  18080. vertexSource = baseName.vertexElement;
  18081. }
  18082. }
  18083. else {
  18084. vertexSource = baseName.vertex || baseName;
  18085. }
  18086. if (baseName.fragmentElement) {
  18087. fragmentSource = document.getElementById(baseName.fragmentElement);
  18088. if (!fragmentSource) {
  18089. fragmentSource = baseName.fragmentElement;
  18090. }
  18091. }
  18092. else {
  18093. fragmentSource = baseName.fragment || baseName;
  18094. }
  18095. this._loadVertexShader(vertexSource, function (vertexCode) {
  18096. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18097. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18098. });
  18099. });
  18100. }
  18101. // Properties
  18102. Effect.prototype.isReady = function () {
  18103. return this._isReady;
  18104. };
  18105. Effect.prototype.getProgram = function () {
  18106. return this._program;
  18107. };
  18108. Effect.prototype.getAttributesNames = function () {
  18109. return this._attributesNames;
  18110. };
  18111. Effect.prototype.getAttributeLocation = function (index) {
  18112. return this._attributes[index];
  18113. };
  18114. Effect.prototype.getAttributeLocationByName = function (name) {
  18115. var index = this._attributesNames.indexOf(name);
  18116. return this._attributes[index];
  18117. };
  18118. Effect.prototype.getAttributesCount = function () {
  18119. return this._attributes.length;
  18120. };
  18121. Effect.prototype.getUniformIndex = function (uniformName) {
  18122. return this._uniformsNames.indexOf(uniformName);
  18123. };
  18124. Effect.prototype.getUniform = function (uniformName) {
  18125. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18126. };
  18127. Effect.prototype.getSamplers = function () {
  18128. return this._samplers;
  18129. };
  18130. Effect.prototype.getCompilationError = function () {
  18131. return this._compilationError;
  18132. };
  18133. // Methods
  18134. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18135. // DOM element ?
  18136. if (vertex instanceof HTMLElement) {
  18137. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18138. callback(vertexCode);
  18139. return;
  18140. }
  18141. // Is in local store ?
  18142. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18143. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18144. return;
  18145. }
  18146. var vertexShaderUrl;
  18147. if (vertex[0] === "." || vertex[0] === "/") {
  18148. vertexShaderUrl = vertex;
  18149. }
  18150. else {
  18151. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18152. }
  18153. // Vertex shader
  18154. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18155. };
  18156. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18157. // DOM element ?
  18158. if (fragment instanceof HTMLElement) {
  18159. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18160. callback(fragmentCode);
  18161. return;
  18162. }
  18163. // Is in local store ?
  18164. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18165. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18166. return;
  18167. }
  18168. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18169. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18170. return;
  18171. }
  18172. var fragmentShaderUrl;
  18173. if (fragment[0] === "." || fragment[0] === "/") {
  18174. fragmentShaderUrl = fragment;
  18175. }
  18176. else {
  18177. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18178. }
  18179. // Fragment shader
  18180. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18181. };
  18182. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18183. try {
  18184. var engine = this._engine;
  18185. if (!engine.getCaps().highPrecisionShaderSupported) {
  18186. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18187. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18188. }
  18189. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18190. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18191. this._attributes = engine.getAttributes(this._program, attributesNames);
  18192. for (var index = 0; index < this._samplers.length; index++) {
  18193. var sampler = this.getUniform(this._samplers[index]);
  18194. if (sampler == null) {
  18195. this._samplers.splice(index, 1);
  18196. index--;
  18197. }
  18198. }
  18199. engine.bindSamplers(this);
  18200. this._isReady = true;
  18201. if (this.onCompiled) {
  18202. this.onCompiled(this);
  18203. }
  18204. }
  18205. catch (e) {
  18206. // Is it a problem with precision?
  18207. if (e.message.indexOf("highp") !== -1) {
  18208. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18209. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18210. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18211. return;
  18212. }
  18213. // Let's go through fallbacks then
  18214. if (fallbacks && fallbacks.isMoreFallbacks) {
  18215. defines = fallbacks.reduce(defines);
  18216. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18217. }
  18218. else {
  18219. BABYLON.Tools.Error("Unable to compile effect: ");
  18220. if (this.name.vertexElement) {
  18221. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18222. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18223. }
  18224. else if (this.name.vertex) {
  18225. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18226. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18227. }
  18228. else {
  18229. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18230. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18231. }
  18232. BABYLON.Tools.Error("Defines: " + defines);
  18233. BABYLON.Tools.Error("Error: " + e.message);
  18234. this._compilationError = e.message;
  18235. if (this.onError) {
  18236. this.onError(this, this._compilationError);
  18237. }
  18238. }
  18239. }
  18240. };
  18241. Effect.prototype._bindTexture = function (channel, texture) {
  18242. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18243. };
  18244. Effect.prototype.setTexture = function (channel, texture) {
  18245. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18246. };
  18247. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18248. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18249. };
  18250. //public _cacheMatrix(uniformName, matrix) {
  18251. // if (!this._valueCache[uniformName]) {
  18252. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18253. // }
  18254. // for (var index = 0; index < 16; index++) {
  18255. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18256. // }
  18257. //};
  18258. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18259. if (!this._valueCache[uniformName]) {
  18260. this._valueCache[uniformName] = [x, y];
  18261. return;
  18262. }
  18263. this._valueCache[uniformName][0] = x;
  18264. this._valueCache[uniformName][1] = y;
  18265. };
  18266. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18267. if (!this._valueCache[uniformName]) {
  18268. this._valueCache[uniformName] = [x, y, z];
  18269. return;
  18270. }
  18271. this._valueCache[uniformName][0] = x;
  18272. this._valueCache[uniformName][1] = y;
  18273. this._valueCache[uniformName][2] = z;
  18274. };
  18275. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18276. if (!this._valueCache[uniformName]) {
  18277. this._valueCache[uniformName] = [x, y, z, w];
  18278. return;
  18279. }
  18280. this._valueCache[uniformName][0] = x;
  18281. this._valueCache[uniformName][1] = y;
  18282. this._valueCache[uniformName][2] = z;
  18283. this._valueCache[uniformName][3] = w;
  18284. };
  18285. Effect.prototype.setArray = function (uniformName, array) {
  18286. this._engine.setArray(this.getUniform(uniformName), array);
  18287. return this;
  18288. };
  18289. Effect.prototype.setArray2 = function (uniformName, array) {
  18290. this._engine.setArray2(this.getUniform(uniformName), array);
  18291. return this;
  18292. };
  18293. Effect.prototype.setArray3 = function (uniformName, array) {
  18294. this._engine.setArray3(this.getUniform(uniformName), array);
  18295. return this;
  18296. };
  18297. Effect.prototype.setArray4 = function (uniformName, array) {
  18298. this._engine.setArray4(this.getUniform(uniformName), array);
  18299. return this;
  18300. };
  18301. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18302. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18303. return this;
  18304. };
  18305. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18306. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18307. // return;
  18308. //this._cacheMatrix(uniformName, matrix);
  18309. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18310. return this;
  18311. };
  18312. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18313. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18314. return this;
  18315. };
  18316. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18317. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18318. return this;
  18319. };
  18320. Effect.prototype.setFloat = function (uniformName, value) {
  18321. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18322. return this;
  18323. this._valueCache[uniformName] = value;
  18324. this._engine.setFloat(this.getUniform(uniformName), value);
  18325. return this;
  18326. };
  18327. Effect.prototype.setBool = function (uniformName, bool) {
  18328. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18329. return this;
  18330. this._valueCache[uniformName] = bool;
  18331. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18332. return this;
  18333. };
  18334. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18335. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18336. return this;
  18337. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18338. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18339. return this;
  18340. };
  18341. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18342. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18343. return this;
  18344. this._cacheFloat2(uniformName, x, y);
  18345. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18346. return this;
  18347. };
  18348. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18349. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18350. return this;
  18351. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18352. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18353. return this;
  18354. };
  18355. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18356. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18357. return this;
  18358. this._cacheFloat3(uniformName, x, y, z);
  18359. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18360. return this;
  18361. };
  18362. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18363. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18364. return this;
  18365. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18366. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18367. return this;
  18368. };
  18369. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18370. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18371. return this;
  18372. this._cacheFloat4(uniformName, x, y, z, w);
  18373. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18374. return this;
  18375. };
  18376. Effect.prototype.setColor3 = function (uniformName, color3) {
  18377. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18378. return this;
  18379. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18380. this._engine.setColor3(this.getUniform(uniformName), color3);
  18381. return this;
  18382. };
  18383. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18384. 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)
  18385. return this;
  18386. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18387. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18388. return this;
  18389. };
  18390. // Statics
  18391. Effect.ShadersStore = {};
  18392. return Effect;
  18393. })();
  18394. BABYLON.Effect = Effect;
  18395. })(BABYLON || (BABYLON = {}));
  18396. var BABYLON;
  18397. (function (BABYLON) {
  18398. var Material = (function () {
  18399. function Material(name, scene, doNotAdd) {
  18400. this.name = name;
  18401. this.checkReadyOnEveryCall = true;
  18402. this.checkReadyOnlyOnce = false;
  18403. this.state = "";
  18404. this.alpha = 1.0;
  18405. this.backFaceCulling = true;
  18406. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18407. this.disableDepthWrite = false;
  18408. this._wasPreviouslyReady = false;
  18409. this._fillMode = Material.TriangleFillMode;
  18410. this.pointSize = 1.0;
  18411. this.zOffset = 0;
  18412. this.id = name;
  18413. this._scene = scene;
  18414. if (!doNotAdd) {
  18415. scene.materials.push(this);
  18416. }
  18417. }
  18418. Object.defineProperty(Material, "TriangleFillMode", {
  18419. get: function () {
  18420. return Material._TriangleFillMode;
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. Object.defineProperty(Material, "WireFrameFillMode", {
  18426. get: function () {
  18427. return Material._WireFrameFillMode;
  18428. },
  18429. enumerable: true,
  18430. configurable: true
  18431. });
  18432. Object.defineProperty(Material, "PointFillMode", {
  18433. get: function () {
  18434. return Material._PointFillMode;
  18435. },
  18436. enumerable: true,
  18437. configurable: true
  18438. });
  18439. Object.defineProperty(Material.prototype, "wireframe", {
  18440. get: function () {
  18441. return this._fillMode === Material.WireFrameFillMode;
  18442. },
  18443. set: function (value) {
  18444. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18445. },
  18446. enumerable: true,
  18447. configurable: true
  18448. });
  18449. Object.defineProperty(Material.prototype, "pointsCloud", {
  18450. get: function () {
  18451. return this._fillMode === Material.PointFillMode;
  18452. },
  18453. set: function (value) {
  18454. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(Material.prototype, "fillMode", {
  18460. get: function () {
  18461. return this._fillMode;
  18462. },
  18463. set: function (value) {
  18464. this._fillMode = value;
  18465. },
  18466. enumerable: true,
  18467. configurable: true
  18468. });
  18469. Material.prototype.isReady = function (mesh, useInstances) {
  18470. return true;
  18471. };
  18472. Material.prototype.getEffect = function () {
  18473. return this._effect;
  18474. };
  18475. Material.prototype.getScene = function () {
  18476. return this._scene;
  18477. };
  18478. Material.prototype.needAlphaBlending = function () {
  18479. return (this.alpha < 1.0);
  18480. };
  18481. Material.prototype.needAlphaTesting = function () {
  18482. return false;
  18483. };
  18484. Material.prototype.getAlphaTestTexture = function () {
  18485. return null;
  18486. };
  18487. Material.prototype.trackCreation = function (onCompiled, onError) {
  18488. };
  18489. Material.prototype._preBind = function () {
  18490. var engine = this._scene.getEngine();
  18491. engine.enableEffect(this._effect);
  18492. engine.setState(this.backFaceCulling, this.zOffset);
  18493. };
  18494. Material.prototype.bind = function (world, mesh) {
  18495. this._scene._cachedMaterial = this;
  18496. if (this.onBind) {
  18497. this.onBind(this, mesh);
  18498. }
  18499. if (this.disableDepthWrite) {
  18500. var engine = this._scene.getEngine();
  18501. this._cachedDepthWriteState = engine.getDepthWrite();
  18502. engine.setDepthWrite(false);
  18503. }
  18504. };
  18505. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18506. };
  18507. Material.prototype.unbind = function () {
  18508. if (this.disableDepthWrite) {
  18509. var engine = this._scene.getEngine();
  18510. engine.setDepthWrite(this._cachedDepthWriteState);
  18511. }
  18512. };
  18513. Material.prototype.clone = function (name) {
  18514. return null;
  18515. };
  18516. Material.prototype.dispose = function (forceDisposeEffect) {
  18517. // Remove from scene
  18518. var index = this._scene.materials.indexOf(this);
  18519. this._scene.materials.splice(index, 1);
  18520. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18521. if (forceDisposeEffect && this._effect) {
  18522. this._scene.getEngine()._releaseEffect(this._effect);
  18523. this._effect = null;
  18524. }
  18525. // Callback
  18526. if (this.onDispose) {
  18527. this.onDispose();
  18528. }
  18529. };
  18530. Material._TriangleFillMode = 0;
  18531. Material._WireFrameFillMode = 1;
  18532. Material._PointFillMode = 2;
  18533. return Material;
  18534. })();
  18535. BABYLON.Material = Material;
  18536. })(BABYLON || (BABYLON = {}));
  18537. var BABYLON;
  18538. (function (BABYLON) {
  18539. var maxSimultaneousLights = 4;
  18540. var FresnelParameters = (function () {
  18541. function FresnelParameters() {
  18542. this.isEnabled = true;
  18543. this.leftColor = BABYLON.Color3.White();
  18544. this.rightColor = BABYLON.Color3.Black();
  18545. this.bias = 0;
  18546. this.power = 1;
  18547. }
  18548. return FresnelParameters;
  18549. })();
  18550. BABYLON.FresnelParameters = FresnelParameters;
  18551. var StandardMaterialDefines = (function () {
  18552. function StandardMaterialDefines() {
  18553. this.DIFFUSE = false;
  18554. this.AMBIENT = false;
  18555. this.OPACITY = false;
  18556. this.OPACITYRGB = false;
  18557. this.REFLECTION = false;
  18558. this.EMISSIVE = false;
  18559. this.SPECULAR = false;
  18560. this.BUMP = false;
  18561. this.SPECULAROVERALPHA = false;
  18562. this.CLIPPLANE = false;
  18563. this.ALPHATEST = false;
  18564. this.ALPHAFROMDIFFUSE = false;
  18565. this.POINTSIZE = false;
  18566. this.FOG = false;
  18567. this.LIGHT0 = false;
  18568. this.LIGHT1 = false;
  18569. this.LIGHT2 = false;
  18570. this.LIGHT3 = false;
  18571. this.SPOTLIGHT0 = false;
  18572. this.SPOTLIGHT1 = false;
  18573. this.SPOTLIGHT2 = false;
  18574. this.SPOTLIGHT3 = false;
  18575. this.HEMILIGHT0 = false;
  18576. this.HEMILIGHT1 = false;
  18577. this.HEMILIGHT2 = false;
  18578. this.HEMILIGHT3 = false;
  18579. this.POINTDIRLIGHT0 = false;
  18580. this.POINTDIRLIGHT1 = false;
  18581. this.POINTDIRLIGHT2 = false;
  18582. this.POINTDIRLIGHT3 = false;
  18583. this.SPECULARTERM = false;
  18584. this.SHADOW0 = false;
  18585. this.SHADOW1 = false;
  18586. this.SHADOW2 = false;
  18587. this.SHADOW3 = false;
  18588. this.SHADOWS = false;
  18589. this.SHADOWVSM0 = false;
  18590. this.SHADOWVSM1 = false;
  18591. this.SHADOWVSM2 = false;
  18592. this.SHADOWVSM3 = false;
  18593. this.SHADOWPCF0 = false;
  18594. this.SHADOWPCF1 = false;
  18595. this.SHADOWPCF2 = false;
  18596. this.SHADOWPCF3 = false;
  18597. this.DIFFUSEFRESNEL = false;
  18598. this.OPACITYFRESNEL = false;
  18599. this.REFLECTIONFRESNEL = false;
  18600. this.EMISSIVEFRESNEL = false;
  18601. this.FRESNEL = false;
  18602. this.NORMAL = false;
  18603. this.UV1 = false;
  18604. this.UV2 = false;
  18605. this.VERTEXCOLOR = false;
  18606. this.VERTEXALPHA = false;
  18607. this.BONES = false;
  18608. this.BONES4 = false;
  18609. this.BonesPerMesh = 0;
  18610. this.INSTANCES = false;
  18611. this.GLOSSINESS = false;
  18612. this.ROUGHNESS = false;
  18613. this.EMISSIVEASILLUMINATION = false;
  18614. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18615. this._keys = Object.keys(this);
  18616. }
  18617. StandardMaterialDefines.prototype.isEqual = function (other) {
  18618. for (var index = 0; index < this._keys.length; index++) {
  18619. var prop = this._keys[index];
  18620. if (this[prop] !== other[prop]) {
  18621. return false;
  18622. }
  18623. }
  18624. return true;
  18625. };
  18626. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18627. for (var index = 0; index < this._keys.length; index++) {
  18628. var prop = this._keys[index];
  18629. other[prop] = this[prop];
  18630. }
  18631. };
  18632. StandardMaterialDefines.prototype.reset = function () {
  18633. for (var index = 0; index < this._keys.length; index++) {
  18634. var prop = this._keys[index];
  18635. if (prop === "BonesPerMesh") {
  18636. this[prop] = 0;
  18637. continue;
  18638. }
  18639. this[prop] = false;
  18640. }
  18641. };
  18642. StandardMaterialDefines.prototype.toString = function () {
  18643. var result = "";
  18644. for (var index = 0; index < this._keys.length; index++) {
  18645. var prop = this._keys[index];
  18646. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18647. result += "#define BonesPerMesh " + this[prop] + "\n";
  18648. continue;
  18649. }
  18650. if (this[prop]) {
  18651. result += "#define " + prop + "\n";
  18652. }
  18653. }
  18654. return result;
  18655. };
  18656. return StandardMaterialDefines;
  18657. })();
  18658. var StandardMaterial = (function (_super) {
  18659. __extends(StandardMaterial, _super);
  18660. function StandardMaterial(name, scene) {
  18661. var _this = this;
  18662. _super.call(this, name, scene);
  18663. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18664. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18665. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18666. this.specularPower = 64;
  18667. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18668. this.useAlphaFromDiffuseTexture = false;
  18669. this.useEmissiveAsIllumination = false;
  18670. this.useReflectionFresnelFromSpecular = false;
  18671. this.useSpecularOverAlpha = true;
  18672. this.fogEnabled = true;
  18673. this.roughness = 0;
  18674. this.useGlossinessFromSpecularMapAlpha = false;
  18675. this._renderTargets = new BABYLON.SmartArray(16);
  18676. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18677. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18678. this._scaledDiffuse = new BABYLON.Color3();
  18679. this._scaledSpecular = new BABYLON.Color3();
  18680. this._defines = new StandardMaterialDefines();
  18681. this._cachedDefines = new StandardMaterialDefines();
  18682. this._cachedDefines.BonesPerMesh = -1;
  18683. this.getRenderTargetTextures = function () {
  18684. _this._renderTargets.reset();
  18685. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18686. _this._renderTargets.push(_this.reflectionTexture);
  18687. }
  18688. return _this._renderTargets;
  18689. };
  18690. }
  18691. StandardMaterial.prototype.needAlphaBlending = function () {
  18692. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18693. };
  18694. StandardMaterial.prototype.needAlphaTesting = function () {
  18695. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18696. };
  18697. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18698. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18699. };
  18700. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18701. return this.diffuseTexture;
  18702. };
  18703. // Methods
  18704. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18705. if (this.checkReadyOnlyOnce) {
  18706. if (this._wasPreviouslyReady) {
  18707. return true;
  18708. }
  18709. }
  18710. var scene = this.getScene();
  18711. if (!this.checkReadyOnEveryCall) {
  18712. if (this._renderId === scene.getRenderId()) {
  18713. return true;
  18714. }
  18715. }
  18716. var engine = scene.getEngine();
  18717. var needNormals = false;
  18718. var needUVs = false;
  18719. this._defines.reset();
  18720. // Textures
  18721. if (scene.texturesEnabled) {
  18722. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18723. if (!this.diffuseTexture.isReady()) {
  18724. return false;
  18725. }
  18726. else {
  18727. needUVs = true;
  18728. this._defines.DIFFUSE = true;
  18729. }
  18730. }
  18731. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18732. if (!this.ambientTexture.isReady()) {
  18733. return false;
  18734. }
  18735. else {
  18736. needUVs = true;
  18737. this._defines.AMBIENT = true;
  18738. }
  18739. }
  18740. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18741. if (!this.opacityTexture.isReady()) {
  18742. return false;
  18743. }
  18744. else {
  18745. needUVs = true;
  18746. this._defines.OPACITY = true;
  18747. if (this.opacityTexture.getAlphaFromRGB) {
  18748. this._defines.OPACITYRGB = true;
  18749. }
  18750. }
  18751. }
  18752. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18753. if (!this.reflectionTexture.isReady()) {
  18754. return false;
  18755. }
  18756. else {
  18757. needNormals = true;
  18758. needUVs = true;
  18759. this._defines.REFLECTION = true;
  18760. if (this.roughness > 0) {
  18761. this._defines.ROUGHNESS = true;
  18762. }
  18763. }
  18764. }
  18765. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18766. if (!this.emissiveTexture.isReady()) {
  18767. return false;
  18768. }
  18769. else {
  18770. needUVs = true;
  18771. this._defines.EMISSIVE = true;
  18772. }
  18773. }
  18774. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18775. if (!this.specularTexture.isReady()) {
  18776. return false;
  18777. }
  18778. else {
  18779. needUVs = true;
  18780. this._defines.SPECULAR = true;
  18781. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18782. }
  18783. }
  18784. }
  18785. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18786. if (!this.bumpTexture.isReady()) {
  18787. return false;
  18788. }
  18789. else {
  18790. needUVs = true;
  18791. this._defines.BUMP = true;
  18792. }
  18793. }
  18794. // Effect
  18795. if (scene.clipPlane) {
  18796. this._defines.CLIPPLANE = true;
  18797. }
  18798. if (engine.getAlphaTesting()) {
  18799. this._defines.ALPHATEST = true;
  18800. }
  18801. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18802. this._defines.ALPHAFROMDIFFUSE = true;
  18803. }
  18804. if (this.useEmissiveAsIllumination) {
  18805. this._defines.EMISSIVEASILLUMINATION = true;
  18806. }
  18807. if (this.useReflectionFresnelFromSpecular) {
  18808. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18809. }
  18810. // Point size
  18811. if (this.pointsCloud || scene.forcePointsCloud) {
  18812. this._defines.POINTSIZE = true;
  18813. }
  18814. // Fog
  18815. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18816. this._defines.FOG = true;
  18817. }
  18818. var lightIndex = 0;
  18819. if (scene.lightsEnabled) {
  18820. for (var index = 0; index < scene.lights.length; index++) {
  18821. var light = scene.lights[index];
  18822. if (!light.isEnabled()) {
  18823. continue;
  18824. }
  18825. // Excluded check
  18826. if (light._excludedMeshesIds.length > 0) {
  18827. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18828. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18829. if (excludedMesh) {
  18830. light.excludedMeshes.push(excludedMesh);
  18831. }
  18832. }
  18833. light._excludedMeshesIds = [];
  18834. }
  18835. // Included check
  18836. if (light._includedOnlyMeshesIds.length > 0) {
  18837. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18838. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18839. if (includedOnlyMesh) {
  18840. light.includedOnlyMeshes.push(includedOnlyMesh);
  18841. }
  18842. }
  18843. light._includedOnlyMeshesIds = [];
  18844. }
  18845. if (!light.canAffectMesh(mesh)) {
  18846. continue;
  18847. }
  18848. needNormals = true;
  18849. this._defines["LIGHT" + lightIndex] = true;
  18850. var type;
  18851. if (light instanceof BABYLON.SpotLight) {
  18852. type = "SPOTLIGHT" + lightIndex;
  18853. }
  18854. else if (light instanceof BABYLON.HemisphericLight) {
  18855. type = "HEMILIGHT" + lightIndex;
  18856. }
  18857. else {
  18858. type = "POINTDIRLIGHT" + lightIndex;
  18859. }
  18860. this._defines[type] = true;
  18861. // Specular
  18862. if (!light.specular.equalsFloats(0, 0, 0)) {
  18863. this._defines.SPECULARTERM = true;
  18864. }
  18865. // Shadows
  18866. if (scene.shadowsEnabled) {
  18867. var shadowGenerator = light.getShadowGenerator();
  18868. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18869. this._defines["SHADOW" + lightIndex] = true;
  18870. this._defines.SHADOWS = true;
  18871. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18872. this._defines["SHADOWVSM" + lightIndex] = true;
  18873. }
  18874. if (shadowGenerator.usePoissonSampling) {
  18875. this._defines["SHADOWPCF" + lightIndex] = true;
  18876. }
  18877. }
  18878. }
  18879. lightIndex++;
  18880. if (lightIndex === maxSimultaneousLights)
  18881. break;
  18882. }
  18883. }
  18884. if (StandardMaterial.FresnelEnabled) {
  18885. // Fresnel
  18886. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18887. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18888. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18889. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18890. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18891. this._defines.DIFFUSEFRESNEL = true;
  18892. }
  18893. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18894. this._defines.OPACITYFRESNEL = true;
  18895. }
  18896. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18897. this._defines.REFLECTIONFRESNEL = true;
  18898. }
  18899. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18900. this._defines.EMISSIVEFRESNEL = true;
  18901. }
  18902. needNormals = true;
  18903. this._defines.FRESNEL = true;
  18904. }
  18905. }
  18906. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18907. this._defines.SPECULAROVERALPHA = true;
  18908. }
  18909. // Attribs
  18910. if (mesh) {
  18911. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18912. this._defines.NORMAL = true;
  18913. }
  18914. if (needUVs) {
  18915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18916. this._defines.UV1 = true;
  18917. }
  18918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18919. this._defines.UV2 = true;
  18920. }
  18921. }
  18922. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18923. this._defines.VERTEXCOLOR = true;
  18924. if (mesh.hasVertexAlpha) {
  18925. this._defines.VERTEXALPHA = true;
  18926. }
  18927. }
  18928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18929. this._defines.BONES = true;
  18930. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18931. this._defines.BONES4 = true;
  18932. }
  18933. // Instances
  18934. if (useInstances) {
  18935. this._defines.INSTANCES = true;
  18936. }
  18937. }
  18938. // Get correct effect
  18939. if (!this._defines.isEqual(this._cachedDefines)) {
  18940. this._defines.cloneTo(this._cachedDefines);
  18941. scene.resetCachedMaterial();
  18942. // Fallbacks
  18943. var fallbacks = new BABYLON.EffectFallbacks();
  18944. if (this._defines.REFLECTION) {
  18945. fallbacks.addFallback(0, "REFLECTION");
  18946. }
  18947. if (this._defines.SPECULAR) {
  18948. fallbacks.addFallback(0, "SPECULAR");
  18949. }
  18950. if (this._defines.BUMP) {
  18951. fallbacks.addFallback(0, "BUMP");
  18952. }
  18953. if (this._defines.SPECULAROVERALPHA) {
  18954. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18955. }
  18956. if (this._defines.FOG) {
  18957. fallbacks.addFallback(1, "FOG");
  18958. }
  18959. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18960. if (!this._defines["LIGHT" + lightIndex]) {
  18961. continue;
  18962. }
  18963. if (lightIndex > 0) {
  18964. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18965. }
  18966. if (this._defines["SHADOW" + lightIndex]) {
  18967. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18968. }
  18969. if (this._defines["SHADOWPCF" + lightIndex]) {
  18970. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18971. }
  18972. if (this._defines["SHADOWVSM" + lightIndex]) {
  18973. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18974. }
  18975. }
  18976. if (this._defines.SPECULARTERM) {
  18977. fallbacks.addFallback(0, "SPECULARTERM");
  18978. }
  18979. if (this._defines.DIFFUSEFRESNEL) {
  18980. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18981. }
  18982. if (this._defines.OPACITYFRESNEL) {
  18983. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18984. }
  18985. if (this._defines.REFLECTIONFRESNEL) {
  18986. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18987. }
  18988. if (this._defines.EMISSIVEFRESNEL) {
  18989. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18990. }
  18991. if (this._defines.FRESNEL) {
  18992. fallbacks.addFallback(4, "FRESNEL");
  18993. }
  18994. if (this._defines.BONES4) {
  18995. fallbacks.addFallback(0, "BONES4");
  18996. }
  18997. //Attributes
  18998. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18999. if (this._defines.NORMAL) {
  19000. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19001. }
  19002. if (this._defines.UV1) {
  19003. attribs.push(BABYLON.VertexBuffer.UVKind);
  19004. }
  19005. if (this._defines.UV2) {
  19006. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19007. }
  19008. if (this._defines.VERTEXCOLOR) {
  19009. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19010. }
  19011. if (this._defines.BONES) {
  19012. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19013. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19014. }
  19015. if (this._defines.INSTANCES) {
  19016. attribs.push("world0");
  19017. attribs.push("world1");
  19018. attribs.push("world2");
  19019. attribs.push("world3");
  19020. }
  19021. // Legacy browser patch
  19022. var shaderName = "default";
  19023. if (!scene.getEngine().getCaps().standardDerivatives) {
  19024. shaderName = "legacydefault";
  19025. }
  19026. var join = this._defines.toString();
  19027. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19028. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19029. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19030. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19031. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19032. "vFogInfos", "vFogColor", "pointSize",
  19033. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  19034. "mBones",
  19035. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  19036. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19037. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19038. "roughness"
  19039. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  19040. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19041. ], join, fallbacks, this.onCompiled, this.onError);
  19042. }
  19043. if (!this._effect.isReady()) {
  19044. return false;
  19045. }
  19046. this._renderId = scene.getRenderId();
  19047. this._wasPreviouslyReady = true;
  19048. return true;
  19049. };
  19050. StandardMaterial.prototype.unbind = function () {
  19051. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19052. this._effect.setTexture("reflection2DSampler", null);
  19053. }
  19054. _super.prototype.unbind.call(this);
  19055. };
  19056. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19057. this._effect.setMatrix("world", world);
  19058. };
  19059. StandardMaterial.prototype.bind = function (world, mesh) {
  19060. var scene = this.getScene();
  19061. // Matrices
  19062. this.bindOnlyWorldMatrix(world);
  19063. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19064. // Bones
  19065. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19066. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19067. }
  19068. if (scene.getCachedMaterial() !== this) {
  19069. if (StandardMaterial.FresnelEnabled) {
  19070. // Fresnel
  19071. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19072. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19073. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19074. }
  19075. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19076. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19077. }
  19078. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19079. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19080. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19081. }
  19082. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19083. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19084. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19085. }
  19086. }
  19087. // Textures
  19088. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19089. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19090. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19091. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19092. }
  19093. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19094. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19095. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19096. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19097. }
  19098. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19099. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19100. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19101. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19102. }
  19103. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19104. if (this.reflectionTexture.isCube) {
  19105. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19106. if (this._defines.ROUGHNESS) {
  19107. this._effect.setFloat("roughness", this.roughness);
  19108. }
  19109. }
  19110. else {
  19111. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19112. }
  19113. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19114. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19115. }
  19116. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19117. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19118. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19119. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19120. }
  19121. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19122. this._effect.setTexture("specularSampler", this.specularTexture);
  19123. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19124. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19125. }
  19126. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19127. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19128. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19129. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19130. }
  19131. // Clip plane
  19132. if (scene.clipPlane) {
  19133. var clipPlane = scene.clipPlane;
  19134. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19135. }
  19136. // Point size
  19137. if (this.pointsCloud) {
  19138. this._effect.setFloat("pointSize", this.pointSize);
  19139. }
  19140. // Colors
  19141. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19142. // Scaling down color according to emissive
  19143. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19144. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19145. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19146. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19147. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19148. if (this._defines.SPECULARTERM) {
  19149. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19150. }
  19151. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19152. }
  19153. // Scaling down color according to emissive
  19154. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19155. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19156. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19157. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19158. if (scene.lightsEnabled) {
  19159. var lightIndex = 0;
  19160. for (var index = 0; index < scene.lights.length; index++) {
  19161. var light = scene.lights[index];
  19162. if (!light.isEnabled()) {
  19163. continue;
  19164. }
  19165. if (!light.canAffectMesh(mesh)) {
  19166. continue;
  19167. }
  19168. if (light instanceof BABYLON.PointLight) {
  19169. // Point Light
  19170. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19171. }
  19172. else if (light instanceof BABYLON.DirectionalLight) {
  19173. // Directional Light
  19174. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19175. }
  19176. else if (light instanceof BABYLON.SpotLight) {
  19177. // Spot Light
  19178. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19179. }
  19180. else if (light instanceof BABYLON.HemisphericLight) {
  19181. // Hemispheric Light
  19182. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19183. }
  19184. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19185. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19186. if (this._defines.SPECULARTERM) {
  19187. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19188. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19189. }
  19190. // Shadows
  19191. if (scene.shadowsEnabled) {
  19192. var shadowGenerator = light.getShadowGenerator();
  19193. if (mesh.receiveShadows && shadowGenerator) {
  19194. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19195. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19196. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19197. }
  19198. }
  19199. lightIndex++;
  19200. if (lightIndex === maxSimultaneousLights)
  19201. break;
  19202. }
  19203. }
  19204. // View
  19205. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19206. this._effect.setMatrix("view", scene.getViewMatrix());
  19207. }
  19208. // Fog
  19209. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19210. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19211. this._effect.setColor3("vFogColor", scene.fogColor);
  19212. }
  19213. _super.prototype.bind.call(this, world, mesh);
  19214. };
  19215. StandardMaterial.prototype.getAnimatables = function () {
  19216. var results = [];
  19217. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19218. results.push(this.diffuseTexture);
  19219. }
  19220. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19221. results.push(this.ambientTexture);
  19222. }
  19223. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19224. results.push(this.opacityTexture);
  19225. }
  19226. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19227. results.push(this.reflectionTexture);
  19228. }
  19229. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19230. results.push(this.emissiveTexture);
  19231. }
  19232. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19233. results.push(this.specularTexture);
  19234. }
  19235. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19236. results.push(this.bumpTexture);
  19237. }
  19238. return results;
  19239. };
  19240. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19241. if (this.diffuseTexture) {
  19242. this.diffuseTexture.dispose();
  19243. }
  19244. if (this.ambientTexture) {
  19245. this.ambientTexture.dispose();
  19246. }
  19247. if (this.opacityTexture) {
  19248. this.opacityTexture.dispose();
  19249. }
  19250. if (this.reflectionTexture) {
  19251. this.reflectionTexture.dispose();
  19252. }
  19253. if (this.emissiveTexture) {
  19254. this.emissiveTexture.dispose();
  19255. }
  19256. if (this.specularTexture) {
  19257. this.specularTexture.dispose();
  19258. }
  19259. if (this.bumpTexture) {
  19260. this.bumpTexture.dispose();
  19261. }
  19262. _super.prototype.dispose.call(this, forceDisposeEffect);
  19263. };
  19264. StandardMaterial.prototype.clone = function (name) {
  19265. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19266. // Base material
  19267. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19268. newStandardMaterial.alpha = this.alpha;
  19269. newStandardMaterial.fillMode = this.fillMode;
  19270. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19271. // Standard material
  19272. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19273. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19274. }
  19275. if (this.ambientTexture && this.ambientTexture.clone) {
  19276. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19277. }
  19278. if (this.opacityTexture && this.opacityTexture.clone) {
  19279. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19280. }
  19281. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19282. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19283. }
  19284. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19285. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19286. }
  19287. if (this.specularTexture && this.specularTexture.clone) {
  19288. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19289. }
  19290. if (this.bumpTexture && this.bumpTexture.clone) {
  19291. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19292. }
  19293. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19294. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19295. newStandardMaterial.specularColor = this.specularColor.clone();
  19296. newStandardMaterial.specularPower = this.specularPower;
  19297. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19298. return newStandardMaterial;
  19299. };
  19300. // Statics
  19301. // Flags used to enable or disable a type of texture for all Standard Materials
  19302. StandardMaterial.DiffuseTextureEnabled = true;
  19303. StandardMaterial.AmbientTextureEnabled = true;
  19304. StandardMaterial.OpacityTextureEnabled = true;
  19305. StandardMaterial.ReflectionTextureEnabled = true;
  19306. StandardMaterial.EmissiveTextureEnabled = true;
  19307. StandardMaterial.SpecularTextureEnabled = true;
  19308. StandardMaterial.BumpTextureEnabled = true;
  19309. StandardMaterial.FresnelEnabled = true;
  19310. return StandardMaterial;
  19311. })(BABYLON.Material);
  19312. BABYLON.StandardMaterial = StandardMaterial;
  19313. })(BABYLON || (BABYLON = {}));
  19314. var BABYLON;
  19315. (function (BABYLON) {
  19316. var MultiMaterial = (function (_super) {
  19317. __extends(MultiMaterial, _super);
  19318. function MultiMaterial(name, scene) {
  19319. _super.call(this, name, scene, true);
  19320. this.subMaterials = new Array();
  19321. scene.multiMaterials.push(this);
  19322. }
  19323. // Properties
  19324. MultiMaterial.prototype.getSubMaterial = function (index) {
  19325. if (index < 0 || index >= this.subMaterials.length) {
  19326. return this.getScene().defaultMaterial;
  19327. }
  19328. return this.subMaterials[index];
  19329. };
  19330. // Methods
  19331. MultiMaterial.prototype.isReady = function (mesh) {
  19332. for (var index = 0; index < this.subMaterials.length; index++) {
  19333. var subMaterial = this.subMaterials[index];
  19334. if (subMaterial) {
  19335. if (!this.subMaterials[index].isReady(mesh)) {
  19336. return false;
  19337. }
  19338. }
  19339. }
  19340. return true;
  19341. };
  19342. MultiMaterial.prototype.clone = function (name) {
  19343. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19344. for (var index = 0; index < this.subMaterials.length; index++) {
  19345. var subMaterial = this.subMaterials[index];
  19346. newMultiMaterial.subMaterials.push(subMaterial);
  19347. }
  19348. return newMultiMaterial;
  19349. };
  19350. return MultiMaterial;
  19351. })(BABYLON.Material);
  19352. BABYLON.MultiMaterial = MultiMaterial;
  19353. })(BABYLON || (BABYLON = {}));
  19354. var BABYLON;
  19355. (function (BABYLON) {
  19356. var SceneLoader = (function () {
  19357. function SceneLoader() {
  19358. }
  19359. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19360. get: function () {
  19361. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19362. },
  19363. set: function (value) {
  19364. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19370. get: function () {
  19371. return SceneLoader._ShowLoadingScreen;
  19372. },
  19373. set: function (value) {
  19374. SceneLoader._ShowLoadingScreen = value;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19380. var dotPosition = sceneFilename.lastIndexOf(".");
  19381. var queryStringPosition = sceneFilename.indexOf("?");
  19382. if (queryStringPosition === -1) {
  19383. queryStringPosition = sceneFilename.length;
  19384. }
  19385. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19386. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19387. var plugin = this._registeredPlugins[index];
  19388. if (plugin.extensions.indexOf(extension) !== -1) {
  19389. return plugin;
  19390. }
  19391. }
  19392. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19393. };
  19394. // Public functions
  19395. SceneLoader.RegisterPlugin = function (plugin) {
  19396. plugin.extensions = plugin.extensions.toLowerCase();
  19397. SceneLoader._registeredPlugins.push(plugin);
  19398. };
  19399. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19400. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19401. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19402. return;
  19403. }
  19404. var loadingToken = {};
  19405. scene._addPendingData(loadingToken);
  19406. var manifestChecked = function (success) {
  19407. scene.database = database;
  19408. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19409. var importMeshFromData = function (data) {
  19410. var meshes = [];
  19411. var particleSystems = [];
  19412. var skeletons = [];
  19413. try {
  19414. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19415. if (onerror) {
  19416. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19417. }
  19418. scene._removePendingData(loadingToken);
  19419. return;
  19420. }
  19421. }
  19422. catch (e) {
  19423. if (onerror) {
  19424. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19425. }
  19426. scene._removePendingData(loadingToken);
  19427. return;
  19428. }
  19429. if (onsuccess) {
  19430. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19431. onsuccess(meshes, particleSystems, skeletons);
  19432. scene._removePendingData(loadingToken);
  19433. }
  19434. };
  19435. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19436. // Direct load
  19437. importMeshFromData(sceneFilename.substr(5));
  19438. return;
  19439. }
  19440. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19441. importMeshFromData(data);
  19442. }, progressCallBack, database);
  19443. };
  19444. if (scene.getEngine().enableOfflineSupport) {
  19445. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19446. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19447. }
  19448. else {
  19449. manifestChecked(true);
  19450. }
  19451. };
  19452. /**
  19453. * Load a scene
  19454. * @param rootUrl a string that defines the root url for scene and resources
  19455. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19456. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19457. */
  19458. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19459. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19460. };
  19461. /**
  19462. * Append a scene
  19463. * @param rootUrl a string that defines the root url for scene and resources
  19464. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19465. * @param scene is the instance of BABYLON.Scene to append to
  19466. */
  19467. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19468. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19469. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19470. return;
  19471. }
  19472. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19473. var database;
  19474. var loadingToken = {};
  19475. scene._addPendingData(loadingToken);
  19476. if (SceneLoader.ShowLoadingScreen) {
  19477. scene.getEngine().displayLoadingUI();
  19478. }
  19479. var loadSceneFromData = function (data) {
  19480. scene.database = database;
  19481. if (!plugin.load(scene, data, rootUrl)) {
  19482. if (onerror) {
  19483. onerror(scene);
  19484. }
  19485. scene._removePendingData(loadingToken);
  19486. scene.getEngine().hideLoadingUI();
  19487. return;
  19488. }
  19489. if (onsuccess) {
  19490. onsuccess(scene);
  19491. }
  19492. scene._removePendingData(loadingToken);
  19493. if (SceneLoader.ShowLoadingScreen) {
  19494. scene.executeWhenReady(function () {
  19495. scene.getEngine().hideLoadingUI();
  19496. });
  19497. }
  19498. };
  19499. var manifestChecked = function (success) {
  19500. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19501. };
  19502. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19503. // Direct load
  19504. loadSceneFromData(sceneFilename.substr(5));
  19505. return;
  19506. }
  19507. if (rootUrl.indexOf("file:") === -1) {
  19508. if (scene.getEngine().enableOfflineSupport) {
  19509. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19510. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19511. }
  19512. else {
  19513. manifestChecked(true);
  19514. }
  19515. }
  19516. else {
  19517. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19518. }
  19519. };
  19520. // Flags
  19521. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19522. SceneLoader._ShowLoadingScreen = true;
  19523. // Members
  19524. SceneLoader._registeredPlugins = new Array();
  19525. return SceneLoader;
  19526. })();
  19527. BABYLON.SceneLoader = SceneLoader;
  19528. ;
  19529. })(BABYLON || (BABYLON = {}));
  19530. var BABYLON;
  19531. (function (BABYLON) {
  19532. var Internals;
  19533. (function (Internals) {
  19534. var checkColors4 = function (colors, count) {
  19535. // Check if color3 was used
  19536. if (colors.length === count * 3) {
  19537. var colors4 = [];
  19538. for (var index = 0; index < colors.length; index += 3) {
  19539. var newIndex = (index / 3) * 4;
  19540. colors4[newIndex] = colors[index];
  19541. colors4[newIndex + 1] = colors[index + 1];
  19542. colors4[newIndex + 2] = colors[index + 2];
  19543. colors4[newIndex + 3] = 1.0;
  19544. }
  19545. return colors4;
  19546. }
  19547. return colors;
  19548. };
  19549. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19550. var texture = null;
  19551. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19552. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19553. texture.name = parsedTexture.name;
  19554. texture.hasAlpha = parsedTexture.hasAlpha;
  19555. texture.level = parsedTexture.level;
  19556. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19557. }
  19558. return texture;
  19559. };
  19560. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19561. if (parsedTexture.isCube) {
  19562. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19563. }
  19564. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19565. return null;
  19566. }
  19567. var texture;
  19568. if (parsedTexture.mirrorPlane) {
  19569. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19570. texture._waitingRenderList = parsedTexture.renderList;
  19571. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19572. }
  19573. else if (parsedTexture.isRenderTarget) {
  19574. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19575. texture._waitingRenderList = parsedTexture.renderList;
  19576. }
  19577. else {
  19578. if (parsedTexture.base64String) {
  19579. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19580. }
  19581. else {
  19582. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19583. }
  19584. }
  19585. texture.name = parsedTexture.name;
  19586. texture.hasAlpha = parsedTexture.hasAlpha;
  19587. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19588. texture.level = parsedTexture.level;
  19589. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19590. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19591. texture.uOffset = parsedTexture.uOffset;
  19592. texture.vOffset = parsedTexture.vOffset;
  19593. texture.uScale = parsedTexture.uScale;
  19594. texture.vScale = parsedTexture.vScale;
  19595. texture.uAng = parsedTexture.uAng;
  19596. texture.vAng = parsedTexture.vAng;
  19597. texture.wAng = parsedTexture.wAng;
  19598. texture.wrapU = parsedTexture.wrapU;
  19599. texture.wrapV = parsedTexture.wrapV;
  19600. // Animations
  19601. if (parsedTexture.animations) {
  19602. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19603. var parsedAnimation = parsedTexture.animations[animationIndex];
  19604. texture.animations.push(parseAnimation(parsedAnimation));
  19605. }
  19606. }
  19607. return texture;
  19608. };
  19609. var parseSkeleton = function (parsedSkeleton, scene) {
  19610. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19611. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19612. var parsedBone = parsedSkeleton.bones[index];
  19613. var parentBone = null;
  19614. if (parsedBone.parentBoneIndex > -1) {
  19615. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19616. }
  19617. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19618. if (parsedBone.animation) {
  19619. bone.animations.push(parseAnimation(parsedBone.animation));
  19620. }
  19621. }
  19622. return skeleton;
  19623. };
  19624. var parseFresnelParameters = function (parsedFresnelParameters) {
  19625. var fresnelParameters = new BABYLON.FresnelParameters();
  19626. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19627. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19628. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19629. fresnelParameters.bias = parsedFresnelParameters.bias;
  19630. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19631. return fresnelParameters;
  19632. };
  19633. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19634. var material;
  19635. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19636. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19637. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19638. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19639. material.specularPower = parsedMaterial.specularPower;
  19640. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19641. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19642. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19643. material.alpha = parsedMaterial.alpha;
  19644. material.id = parsedMaterial.id;
  19645. if (parsedMaterial.disableDepthWrite) {
  19646. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19647. }
  19648. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19649. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19650. material.wireframe = parsedMaterial.wireframe;
  19651. if (parsedMaterial.diffuseTexture) {
  19652. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19653. }
  19654. if (parsedMaterial.diffuseFresnelParameters) {
  19655. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19656. }
  19657. if (parsedMaterial.ambientTexture) {
  19658. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19659. }
  19660. if (parsedMaterial.opacityTexture) {
  19661. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19662. }
  19663. if (parsedMaterial.opacityFresnelParameters) {
  19664. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19665. }
  19666. if (parsedMaterial.reflectionTexture) {
  19667. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19668. }
  19669. if (parsedMaterial.reflectionFresnelParameters) {
  19670. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19671. }
  19672. if (parsedMaterial.emissiveTexture) {
  19673. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19674. }
  19675. if (parsedMaterial.emissiveFresnelParameters) {
  19676. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19677. }
  19678. if (parsedMaterial.specularTexture) {
  19679. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19680. }
  19681. if (parsedMaterial.bumpTexture) {
  19682. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19683. }
  19684. if (parsedMaterial.checkReadyOnlyOnce) {
  19685. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19686. }
  19687. return material;
  19688. };
  19689. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19690. for (var index = 0; index < parsedData.materials.length; index++) {
  19691. var parsedMaterial = parsedData.materials[index];
  19692. if (parsedMaterial.id === id) {
  19693. return parseMaterial(parsedMaterial, scene, rootUrl);
  19694. }
  19695. }
  19696. return null;
  19697. };
  19698. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19699. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19700. multiMaterial.id = parsedMultiMaterial.id;
  19701. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19702. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19703. var subMatId = parsedMultiMaterial.materials[matIndex];
  19704. if (subMatId) {
  19705. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19706. }
  19707. else {
  19708. multiMaterial.subMaterials.push(null);
  19709. }
  19710. }
  19711. return multiMaterial;
  19712. };
  19713. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19714. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19715. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19716. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19717. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19718. var parsedFlare = parsedLensFlareSystem.flares[index];
  19719. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19720. }
  19721. return lensFlareSystem;
  19722. };
  19723. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19724. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19725. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19726. if (parsedParticleSystem.textureName) {
  19727. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19728. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19729. }
  19730. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19731. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19732. particleSystem.minSize = parsedParticleSystem.minSize;
  19733. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19734. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19735. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19736. particleSystem.emitter = emitter;
  19737. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19738. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19739. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19740. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19741. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19742. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19743. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19744. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19745. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19746. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19747. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19748. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19749. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19750. particleSystem.start();
  19751. return particleSystem;
  19752. };
  19753. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19754. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19755. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19756. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19757. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19758. shadowGenerator.getShadowMap().renderList.push(mesh);
  19759. }
  19760. if (parsedShadowGenerator.usePoissonSampling) {
  19761. shadowGenerator.usePoissonSampling = true;
  19762. }
  19763. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19764. shadowGenerator.useVarianceShadowMap = true;
  19765. }
  19766. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19767. shadowGenerator.useBlurVarianceShadowMap = true;
  19768. if (parsedShadowGenerator.blurScale) {
  19769. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19770. }
  19771. if (parsedShadowGenerator.blurBoxOffset) {
  19772. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19773. }
  19774. }
  19775. if (parsedShadowGenerator.bias !== undefined) {
  19776. shadowGenerator.bias = parsedShadowGenerator.bias;
  19777. }
  19778. return shadowGenerator;
  19779. };
  19780. var parseAnimation = function (parsedAnimation) {
  19781. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19782. var dataType = parsedAnimation.dataType;
  19783. var keys = [];
  19784. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19785. var key = parsedAnimation.keys[index];
  19786. var data;
  19787. switch (dataType) {
  19788. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19789. data = key.values[0];
  19790. break;
  19791. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19792. data = BABYLON.Quaternion.FromArray(key.values);
  19793. break;
  19794. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19795. data = BABYLON.Matrix.FromArray(key.values);
  19796. break;
  19797. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19798. default:
  19799. data = BABYLON.Vector3.FromArray(key.values);
  19800. break;
  19801. }
  19802. keys.push({
  19803. frame: key.frame,
  19804. value: data
  19805. });
  19806. }
  19807. animation.setKeys(keys);
  19808. return animation;
  19809. };
  19810. var parseLight = function (parsedLight, scene) {
  19811. var light;
  19812. switch (parsedLight.type) {
  19813. case 0:
  19814. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19815. break;
  19816. case 1:
  19817. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19818. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19819. break;
  19820. case 2:
  19821. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19822. break;
  19823. case 3:
  19824. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19825. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19826. break;
  19827. }
  19828. light.id = parsedLight.id;
  19829. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19830. if (parsedLight.intensity !== undefined) {
  19831. light.intensity = parsedLight.intensity;
  19832. }
  19833. if (parsedLight.range) {
  19834. light.range = parsedLight.range;
  19835. }
  19836. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19837. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19838. if (parsedLight.excludedMeshesIds) {
  19839. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19840. }
  19841. // Parent
  19842. if (parsedLight.parentId) {
  19843. light._waitingParentId = parsedLight.parentId;
  19844. }
  19845. if (parsedLight.includedOnlyMeshesIds) {
  19846. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19847. }
  19848. // Animations
  19849. if (parsedLight.animations) {
  19850. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19851. var parsedAnimation = parsedLight.animations[animationIndex];
  19852. light.animations.push(parseAnimation(parsedAnimation));
  19853. }
  19854. }
  19855. if (parsedLight.autoAnimate) {
  19856. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19857. }
  19858. };
  19859. var parseCamera = function (parsedCamera, scene) {
  19860. var camera;
  19861. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19862. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19863. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19864. var alpha = parsedCamera.alpha;
  19865. var beta = parsedCamera.beta;
  19866. var radius = parsedCamera.radius;
  19867. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19868. var interaxial_distance = parsedCamera.interaxial_distance;
  19869. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19870. }
  19871. else {
  19872. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19873. }
  19874. }
  19875. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19876. interaxial_distance = parsedCamera.interaxial_distance;
  19877. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19878. }
  19879. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19880. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19881. }
  19882. else if (parsedCamera.type === "FollowCamera") {
  19883. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19884. camera.heightOffset = parsedCamera.heightOffset;
  19885. camera.radius = parsedCamera.radius;
  19886. camera.rotationOffset = parsedCamera.rotationOffset;
  19887. if (lockedTargetMesh)
  19888. camera.target = lockedTargetMesh;
  19889. }
  19890. else if (parsedCamera.type === "GamepadCamera") {
  19891. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19892. }
  19893. else if (parsedCamera.type === "TouchCamera") {
  19894. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19895. }
  19896. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19897. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19898. }
  19899. else if (parsedCamera.type === "WebVRFreeCamera") {
  19900. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19901. }
  19902. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19903. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19904. }
  19905. else {
  19906. // Free Camera is the default value
  19907. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19908. }
  19909. // apply 3d rig, when found
  19910. if (parsedCamera.cameraRigMode) {
  19911. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19912. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19913. }
  19914. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19915. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19916. camera.lockedTarget = lockedTargetMesh;
  19917. }
  19918. camera.id = parsedCamera.id;
  19919. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19920. // Parent
  19921. if (parsedCamera.parentId) {
  19922. camera._waitingParentId = parsedCamera.parentId;
  19923. }
  19924. // Target
  19925. if (parsedCamera.target) {
  19926. if (camera.setTarget) {
  19927. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19928. }
  19929. else {
  19930. //For ArcRotate
  19931. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19932. }
  19933. }
  19934. else {
  19935. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19936. }
  19937. camera.fov = parsedCamera.fov;
  19938. camera.minZ = parsedCamera.minZ;
  19939. camera.maxZ = parsedCamera.maxZ;
  19940. camera.speed = parsedCamera.speed;
  19941. camera.inertia = parsedCamera.inertia;
  19942. camera.checkCollisions = parsedCamera.checkCollisions;
  19943. camera.applyGravity = parsedCamera.applyGravity;
  19944. if (parsedCamera.ellipsoid) {
  19945. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19946. }
  19947. // Animations
  19948. if (parsedCamera.animations) {
  19949. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19950. var parsedAnimation = parsedCamera.animations[animationIndex];
  19951. camera.animations.push(parseAnimation(parsedAnimation));
  19952. }
  19953. }
  19954. if (parsedCamera.autoAnimate) {
  19955. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19956. }
  19957. // Layer Mask
  19958. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19959. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19960. }
  19961. else {
  19962. camera.layerMask = 0x0FFFFFFF;
  19963. }
  19964. return camera;
  19965. };
  19966. var parseGeometry = function (parsedGeometry, scene) {
  19967. var id = parsedGeometry.id;
  19968. return scene.getGeometryByID(id);
  19969. };
  19970. var parseBox = function (parsedBox, scene) {
  19971. if (parseGeometry(parsedBox, scene)) {
  19972. return null; // null since geometry could be something else than a box...
  19973. }
  19974. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19975. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19976. scene.pushGeometry(box, true);
  19977. return box;
  19978. };
  19979. var parseSphere = function (parsedSphere, scene) {
  19980. if (parseGeometry(parsedSphere, scene)) {
  19981. return null; // null since geometry could be something else than a sphere...
  19982. }
  19983. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19984. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19985. scene.pushGeometry(sphere, true);
  19986. return sphere;
  19987. };
  19988. var parseCylinder = function (parsedCylinder, scene) {
  19989. if (parseGeometry(parsedCylinder, scene)) {
  19990. return null; // null since geometry could be something else than a cylinder...
  19991. }
  19992. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19993. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19994. scene.pushGeometry(cylinder, true);
  19995. return cylinder;
  19996. };
  19997. var parseTorus = function (parsedTorus, scene) {
  19998. if (parseGeometry(parsedTorus, scene)) {
  19999. return null; // null since geometry could be something else than a torus...
  20000. }
  20001. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20002. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20003. scene.pushGeometry(torus, true);
  20004. return torus;
  20005. };
  20006. var parseGround = function (parsedGround, scene) {
  20007. if (parseGeometry(parsedGround, scene)) {
  20008. return null; // null since geometry could be something else than a ground...
  20009. }
  20010. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20011. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20012. scene.pushGeometry(ground, true);
  20013. return ground;
  20014. };
  20015. var parsePlane = function (parsedPlane, scene) {
  20016. if (parseGeometry(parsedPlane, scene)) {
  20017. return null; // null since geometry could be something else than a plane...
  20018. }
  20019. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20020. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20021. scene.pushGeometry(plane, true);
  20022. return plane;
  20023. };
  20024. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20025. if (parseGeometry(parsedTorusKnot, scene)) {
  20026. return null; // null since geometry could be something else than a torusKnot...
  20027. }
  20028. 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);
  20029. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20030. scene.pushGeometry(torusKnot, true);
  20031. return torusKnot;
  20032. };
  20033. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20034. if (parseGeometry(parsedVertexData, scene)) {
  20035. return null; // null since geometry could be a primitive
  20036. }
  20037. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20038. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20039. if (parsedVertexData.delayLoadingFile) {
  20040. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20041. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20042. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20043. geometry._delayInfo = [];
  20044. if (parsedVertexData.hasUVs) {
  20045. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20046. }
  20047. if (parsedVertexData.hasUVs2) {
  20048. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20049. }
  20050. if (parsedVertexData.hasUVs3) {
  20051. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20052. }
  20053. if (parsedVertexData.hasUVs4) {
  20054. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20055. }
  20056. if (parsedVertexData.hasUVs5) {
  20057. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20058. }
  20059. if (parsedVertexData.hasUVs6) {
  20060. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20061. }
  20062. if (parsedVertexData.hasColors) {
  20063. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20064. }
  20065. if (parsedVertexData.hasMatricesIndices) {
  20066. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20067. }
  20068. if (parsedVertexData.hasMatricesWeights) {
  20069. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20070. }
  20071. geometry._delayLoadingFunction = importVertexData;
  20072. }
  20073. else {
  20074. importVertexData(parsedVertexData, geometry);
  20075. }
  20076. scene.pushGeometry(geometry, true);
  20077. return geometry;
  20078. };
  20079. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20080. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20081. mesh.id = parsedMesh.id;
  20082. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20083. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20084. if (parsedMesh.rotationQuaternion) {
  20085. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20086. }
  20087. else if (parsedMesh.rotation) {
  20088. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20089. }
  20090. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20091. if (parsedMesh.localMatrix) {
  20092. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20093. }
  20094. else if (parsedMesh.pivotMatrix) {
  20095. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20096. }
  20097. mesh.setEnabled(parsedMesh.isEnabled);
  20098. mesh.isVisible = parsedMesh.isVisible;
  20099. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20100. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20101. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20102. if (parsedMesh.applyFog !== undefined) {
  20103. mesh.applyFog = parsedMesh.applyFog;
  20104. }
  20105. if (parsedMesh.pickable !== undefined) {
  20106. mesh.isPickable = parsedMesh.pickable;
  20107. }
  20108. if (parsedMesh.alphaIndex !== undefined) {
  20109. mesh.alphaIndex = parsedMesh.alphaIndex;
  20110. }
  20111. mesh.receiveShadows = parsedMesh.receiveShadows;
  20112. mesh.billboardMode = parsedMesh.billboardMode;
  20113. if (parsedMesh.visibility !== undefined) {
  20114. mesh.visibility = parsedMesh.visibility;
  20115. }
  20116. mesh.checkCollisions = parsedMesh.checkCollisions;
  20117. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20118. // freezeWorldMatrix
  20119. if (parsedMesh.freezeWorldMatrix) {
  20120. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20121. }
  20122. // Parent
  20123. if (parsedMesh.parentId) {
  20124. mesh._waitingParentId = parsedMesh.parentId;
  20125. }
  20126. // Actions
  20127. if (parsedMesh.actions !== undefined) {
  20128. mesh._waitingActions = parsedMesh.actions;
  20129. }
  20130. // Geometry
  20131. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20132. if (parsedMesh.delayLoadingFile) {
  20133. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20134. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20135. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20136. if (parsedMesh._binaryInfo) {
  20137. mesh._binaryInfo = parsedMesh._binaryInfo;
  20138. }
  20139. mesh._delayInfo = [];
  20140. if (parsedMesh.hasUVs) {
  20141. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20142. }
  20143. if (parsedMesh.hasUVs2) {
  20144. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20145. }
  20146. if (parsedMesh.hasUVs3) {
  20147. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20148. }
  20149. if (parsedMesh.hasUVs4) {
  20150. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20151. }
  20152. if (parsedMesh.hasUVs5) {
  20153. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20154. }
  20155. if (parsedMesh.hasUVs6) {
  20156. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20157. }
  20158. if (parsedMesh.hasColors) {
  20159. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20160. }
  20161. if (parsedMesh.hasMatricesIndices) {
  20162. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20163. }
  20164. if (parsedMesh.hasMatricesWeights) {
  20165. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20166. }
  20167. mesh._delayLoadingFunction = importGeometry;
  20168. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20169. mesh._checkDelayState();
  20170. }
  20171. }
  20172. else {
  20173. importGeometry(parsedMesh, mesh);
  20174. }
  20175. // Material
  20176. if (parsedMesh.materialId) {
  20177. mesh.setMaterialByID(parsedMesh.materialId);
  20178. }
  20179. else {
  20180. mesh.material = null;
  20181. }
  20182. // Skeleton
  20183. if (parsedMesh.skeletonId > -1) {
  20184. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20185. }
  20186. // Physics
  20187. if (parsedMesh.physicsImpostor) {
  20188. if (!scene.isPhysicsEnabled()) {
  20189. scene.enablePhysics();
  20190. }
  20191. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20192. }
  20193. // Animations
  20194. if (parsedMesh.animations) {
  20195. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20196. var parsedAnimation = parsedMesh.animations[animationIndex];
  20197. mesh.animations.push(parseAnimation(parsedAnimation));
  20198. }
  20199. }
  20200. if (parsedMesh.autoAnimate) {
  20201. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20202. }
  20203. // Layer Mask
  20204. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20205. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20206. }
  20207. else {
  20208. mesh.layerMask = 0x0FFFFFFF;
  20209. }
  20210. // Instances
  20211. if (parsedMesh.instances) {
  20212. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20213. var parsedInstance = parsedMesh.instances[index];
  20214. var instance = mesh.createInstance(parsedInstance.name);
  20215. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20216. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20217. if (parsedInstance.rotationQuaternion) {
  20218. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20219. }
  20220. else if (parsedInstance.rotation) {
  20221. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20222. }
  20223. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20224. instance.checkCollisions = mesh.checkCollisions;
  20225. if (parsedMesh.animations) {
  20226. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20227. parsedAnimation = parsedMesh.animations[animationIndex];
  20228. instance.animations.push(parseAnimation(parsedAnimation));
  20229. }
  20230. }
  20231. }
  20232. }
  20233. return mesh;
  20234. };
  20235. var parseActions = function (parsedActions, object, scene) {
  20236. var actionManager = new BABYLON.ActionManager(scene);
  20237. if (object === null)
  20238. scene.actionManager = actionManager;
  20239. else
  20240. object.actionManager = actionManager;
  20241. // instanciate a new object
  20242. var instanciate = function (name, params) {
  20243. var newInstance = Object.create(BABYLON[name].prototype);
  20244. newInstance.constructor.apply(newInstance, params);
  20245. return newInstance;
  20246. };
  20247. var parseParameter = function (name, value, target, propertyPath) {
  20248. if (propertyPath === null) {
  20249. // String, boolean or float
  20250. var floatValue = parseFloat(value);
  20251. if (value === "true" || value === "false")
  20252. return value === "true";
  20253. else
  20254. return isNaN(floatValue) ? value : floatValue;
  20255. }
  20256. var effectiveTarget = propertyPath.split(".");
  20257. var values = value.split(",");
  20258. // Get effective Target
  20259. for (var i = 0; i < effectiveTarget.length; i++) {
  20260. target = target[effectiveTarget[i]];
  20261. }
  20262. // Return appropriate value with its type
  20263. if (typeof (target) === "boolean")
  20264. return values[0] === "true";
  20265. if (typeof (target) === "string")
  20266. return values[0];
  20267. // Parameters with multiple values such as Vector3 etc.
  20268. var split = new Array();
  20269. for (var i = 0; i < values.length; i++)
  20270. split.push(parseFloat(values[i]));
  20271. if (target instanceof BABYLON.Vector3)
  20272. return BABYLON.Vector3.FromArray(split);
  20273. if (target instanceof BABYLON.Vector4)
  20274. return BABYLON.Vector4.FromArray(split);
  20275. if (target instanceof BABYLON.Color3)
  20276. return BABYLON.Color3.FromArray(split);
  20277. if (target instanceof BABYLON.Color4)
  20278. return BABYLON.Color4.FromArray(split);
  20279. return parseFloat(values[0]);
  20280. };
  20281. // traverse graph per trigger
  20282. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20283. if (combineArray === void 0) { combineArray = null; }
  20284. if (parsedAction.detached)
  20285. return;
  20286. var parameters = new Array();
  20287. var target = null;
  20288. var propertyPath = null;
  20289. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20290. // Parameters
  20291. if (parsedAction.type === 2)
  20292. parameters.push(actionManager);
  20293. else
  20294. parameters.push(trigger);
  20295. if (combine) {
  20296. var actions = new Array();
  20297. for (var j = 0; j < parsedAction.combine.length; j++) {
  20298. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20299. }
  20300. parameters.push(actions);
  20301. }
  20302. else {
  20303. for (var i = 0; i < parsedAction.properties.length; i++) {
  20304. var value = parsedAction.properties[i].value;
  20305. var name = parsedAction.properties[i].name;
  20306. var targetType = parsedAction.properties[i].targetType;
  20307. if (name === "target")
  20308. if (targetType !== null && targetType === "SceneProperties")
  20309. value = target = scene;
  20310. else
  20311. value = target = scene.getNodeByName(value);
  20312. else if (name === "parent")
  20313. value = scene.getNodeByName(value);
  20314. else if (name === "sound")
  20315. value = scene.getSoundByName(value);
  20316. else if (name !== "propertyPath") {
  20317. if (parsedAction.type === 2 && name === "operator")
  20318. value = BABYLON.ValueCondition[value];
  20319. else
  20320. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20321. }
  20322. else {
  20323. propertyPath = value;
  20324. }
  20325. parameters.push(value);
  20326. }
  20327. }
  20328. if (combineArray === null) {
  20329. parameters.push(condition);
  20330. }
  20331. else {
  20332. parameters.push(null);
  20333. }
  20334. // If interpolate value action
  20335. if (parsedAction.name === "InterpolateValueAction") {
  20336. var param = parameters[parameters.length - 2];
  20337. parameters[parameters.length - 1] = param;
  20338. parameters[parameters.length - 2] = condition;
  20339. }
  20340. // Action or condition(s) and not CombineAction
  20341. var newAction = instanciate(parsedAction.name, parameters);
  20342. if (combineArray === null) {
  20343. if (newAction instanceof BABYLON.Condition) {
  20344. condition = newAction;
  20345. newAction = action;
  20346. }
  20347. else {
  20348. condition = null;
  20349. if (action)
  20350. action.then(newAction);
  20351. else
  20352. actionManager.registerAction(newAction);
  20353. }
  20354. }
  20355. else {
  20356. combineArray.push(newAction);
  20357. }
  20358. for (var i = 0; i < parsedAction.children.length; i++)
  20359. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20360. };
  20361. // triggers
  20362. for (var i = 0; i < parsedActions.children.length; i++) {
  20363. var triggerParams;
  20364. var trigger = parsedActions.children[i];
  20365. if (trigger.properties.length > 0) {
  20366. var param = trigger.properties[0].value;
  20367. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20368. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20369. }
  20370. else
  20371. triggerParams = BABYLON.ActionManager[trigger.name];
  20372. for (var j = 0; j < trigger.children.length; j++) {
  20373. if (!trigger.detached)
  20374. traverse(trigger.children[j], triggerParams, null, null);
  20375. }
  20376. }
  20377. };
  20378. var parseSound = function (parsedSound, scene, rootUrl) {
  20379. var soundName = parsedSound.name;
  20380. var soundUrl = rootUrl + soundName;
  20381. var options = {
  20382. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20383. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20384. rolloffFactor: parsedSound.rolloffFactor,
  20385. refDistance: parsedSound.refDistance,
  20386. distanceModel: parsedSound.distanceModel,
  20387. playbackRate: parsedSound.playbackRate
  20388. };
  20389. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20390. scene._addPendingData(newSound);
  20391. if (parsedSound.position) {
  20392. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20393. newSound.setPosition(soundPosition);
  20394. }
  20395. if (parsedSound.isDirectional) {
  20396. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20397. if (parsedSound.localDirectionToMesh) {
  20398. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20399. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20400. }
  20401. }
  20402. if (parsedSound.connectedMeshId) {
  20403. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20404. if (connectedMesh) {
  20405. newSound.attachToMesh(connectedMesh);
  20406. }
  20407. }
  20408. };
  20409. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20410. names = (names instanceof Array) ? names : [names];
  20411. for (var i in names) {
  20412. if (mesh.name === names[i]) {
  20413. hierarchyIds.push(mesh.id);
  20414. return true;
  20415. }
  20416. }
  20417. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20418. hierarchyIds.push(mesh.id);
  20419. return true;
  20420. }
  20421. return false;
  20422. };
  20423. var importVertexData = function (parsedVertexData, geometry) {
  20424. var vertexData = new BABYLON.VertexData();
  20425. // positions
  20426. var positions = parsedVertexData.positions;
  20427. if (positions) {
  20428. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20429. }
  20430. // normals
  20431. var normals = parsedVertexData.normals;
  20432. if (normals) {
  20433. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20434. }
  20435. // uvs
  20436. var uvs = parsedVertexData.uvs;
  20437. if (uvs) {
  20438. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20439. }
  20440. // uv2s
  20441. var uv2s = parsedVertexData.uv2s;
  20442. if (uv2s) {
  20443. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20444. }
  20445. // uv3s
  20446. var uv3s = parsedVertexData.uv3s;
  20447. if (uv3s) {
  20448. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20449. }
  20450. // uv4s
  20451. var uv4s = parsedVertexData.uv4s;
  20452. if (uv4s) {
  20453. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20454. }
  20455. // uv5s
  20456. var uv5s = parsedVertexData.uv5s;
  20457. if (uv5s) {
  20458. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20459. }
  20460. // uv6s
  20461. var uv6s = parsedVertexData.uv6s;
  20462. if (uv6s) {
  20463. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20464. }
  20465. // colors
  20466. var colors = parsedVertexData.colors;
  20467. if (colors) {
  20468. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20469. }
  20470. // matricesIndices
  20471. var matricesIndices = parsedVertexData.matricesIndices;
  20472. if (matricesIndices) {
  20473. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20474. }
  20475. // matricesWeights
  20476. var matricesWeights = parsedVertexData.matricesWeights;
  20477. if (matricesWeights) {
  20478. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20479. }
  20480. // indices
  20481. var indices = parsedVertexData.indices;
  20482. if (indices) {
  20483. vertexData.indices = indices;
  20484. }
  20485. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20486. };
  20487. var importGeometry = function (parsedGeometry, mesh) {
  20488. var scene = mesh.getScene();
  20489. // Geometry
  20490. var geometryId = parsedGeometry.geometryId;
  20491. if (geometryId) {
  20492. var geometry = scene.getGeometryByID(geometryId);
  20493. if (geometry) {
  20494. geometry.applyToMesh(mesh);
  20495. }
  20496. }
  20497. else if (parsedGeometry instanceof ArrayBuffer) {
  20498. var binaryInfo = mesh._binaryInfo;
  20499. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20500. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20501. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20502. }
  20503. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20504. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20505. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20506. }
  20507. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20508. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20509. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20510. }
  20511. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20512. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20513. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20514. }
  20515. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20516. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20517. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20518. }
  20519. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20520. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20521. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20522. }
  20523. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20524. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20525. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20526. }
  20527. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20528. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20529. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20530. }
  20531. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20532. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20533. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20534. }
  20535. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20536. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20538. }
  20539. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20540. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20541. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20542. }
  20543. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20544. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20545. mesh.setIndices(indicesData);
  20546. }
  20547. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20548. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20549. mesh.subMeshes = [];
  20550. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20551. var materialIndex = subMeshesData[(i * 5) + 0];
  20552. var verticesStart = subMeshesData[(i * 5) + 1];
  20553. var verticesCount = subMeshesData[(i * 5) + 2];
  20554. var indexStart = subMeshesData[(i * 5) + 3];
  20555. var indexCount = subMeshesData[(i * 5) + 4];
  20556. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20557. }
  20558. }
  20559. }
  20560. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20561. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20562. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20563. if (parsedGeometry.uvs) {
  20564. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20565. }
  20566. if (parsedGeometry.uvs2) {
  20567. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20568. }
  20569. if (parsedGeometry.uvs3) {
  20570. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20571. }
  20572. if (parsedGeometry.uvs4) {
  20573. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20574. }
  20575. if (parsedGeometry.uvs5) {
  20576. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20577. }
  20578. if (parsedGeometry.uvs6) {
  20579. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20580. }
  20581. if (parsedGeometry.colors) {
  20582. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20583. }
  20584. if (parsedGeometry.matricesIndices) {
  20585. if (!parsedGeometry.matricesIndices._isExpanded) {
  20586. var floatIndices = [];
  20587. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20588. var matricesIndex = parsedGeometry.matricesIndices[i];
  20589. floatIndices.push(matricesIndex & 0x000000FF);
  20590. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20591. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20592. floatIndices.push(matricesIndex >> 24);
  20593. }
  20594. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20595. }
  20596. else {
  20597. delete parsedGeometry.matricesIndices._isExpanded;
  20598. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20599. }
  20600. }
  20601. if (parsedGeometry.matricesWeights) {
  20602. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20603. }
  20604. mesh.setIndices(parsedGeometry.indices);
  20605. }
  20606. // SubMeshes
  20607. if (parsedGeometry.subMeshes) {
  20608. mesh.subMeshes = [];
  20609. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20610. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20611. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20612. }
  20613. }
  20614. // Flat shading
  20615. if (mesh._shouldGenerateFlatShading) {
  20616. mesh.convertToFlatShadedMesh();
  20617. delete mesh._shouldGenerateFlatShading;
  20618. }
  20619. // Update
  20620. mesh.computeWorldMatrix(true);
  20621. // Octree
  20622. if (scene._selectionOctree) {
  20623. scene._selectionOctree.addMesh(mesh);
  20624. }
  20625. };
  20626. BABYLON.SceneLoader.RegisterPlugin({
  20627. extensions: ".babylon",
  20628. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20629. var parsedData = JSON.parse(data);
  20630. var loadedSkeletonsIds = [];
  20631. var loadedMaterialsIds = [];
  20632. var hierarchyIds = [];
  20633. for (var index = 0; index < parsedData.meshes.length; index++) {
  20634. var parsedMesh = parsedData.meshes[index];
  20635. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20636. if (meshesNames instanceof Array) {
  20637. // Remove found mesh name from list.
  20638. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20639. }
  20640. //Geometry?
  20641. if (parsedMesh.geometryId) {
  20642. //does the file contain geometries?
  20643. if (parsedData.geometries) {
  20644. //find the correct geometry and add it to the scene
  20645. var found = false;
  20646. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20647. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20648. return;
  20649. }
  20650. else {
  20651. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20652. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20653. switch (geometryType) {
  20654. case "boxes":
  20655. parseBox(parsedGeometryData, scene);
  20656. break;
  20657. case "spheres":
  20658. parseSphere(parsedGeometryData, scene);
  20659. break;
  20660. case "cylinders":
  20661. parseCylinder(parsedGeometryData, scene);
  20662. break;
  20663. case "toruses":
  20664. parseTorus(parsedGeometryData, scene);
  20665. break;
  20666. case "grounds":
  20667. parseGround(parsedGeometryData, scene);
  20668. break;
  20669. case "planes":
  20670. parsePlane(parsedGeometryData, scene);
  20671. break;
  20672. case "torusKnots":
  20673. parseTorusKnot(parsedGeometryData, scene);
  20674. break;
  20675. case "vertexData":
  20676. parseVertexData(parsedGeometryData, scene, rootUrl);
  20677. break;
  20678. }
  20679. found = true;
  20680. }
  20681. });
  20682. }
  20683. });
  20684. if (!found) {
  20685. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20686. }
  20687. }
  20688. }
  20689. // Material ?
  20690. if (parsedMesh.materialId) {
  20691. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20692. if (!materialFound && parsedData.multiMaterials) {
  20693. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20694. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20695. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20696. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20697. var subMatId = parsedMultiMaterial.materials[matIndex];
  20698. loadedMaterialsIds.push(subMatId);
  20699. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20700. }
  20701. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20702. parseMultiMaterial(parsedMultiMaterial, scene);
  20703. materialFound = true;
  20704. break;
  20705. }
  20706. }
  20707. }
  20708. if (!materialFound) {
  20709. loadedMaterialsIds.push(parsedMesh.materialId);
  20710. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20711. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20712. }
  20713. }
  20714. }
  20715. // Skeleton ?
  20716. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20717. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20718. if (!skeletonAlreadyLoaded) {
  20719. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20720. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20721. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20722. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20723. loadedSkeletonsIds.push(parsedSkeleton.id);
  20724. }
  20725. }
  20726. }
  20727. }
  20728. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20729. meshes.push(mesh);
  20730. }
  20731. }
  20732. // Connecting parents
  20733. for (index = 0; index < scene.meshes.length; index++) {
  20734. var currentMesh = scene.meshes[index];
  20735. if (currentMesh._waitingParentId) {
  20736. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20737. currentMesh._waitingParentId = undefined;
  20738. }
  20739. }
  20740. // freeze world matrix application
  20741. for (index = 0; index < scene.meshes.length; index++) {
  20742. var currentMesh = scene.meshes[index];
  20743. if (currentMesh._waitingFreezeWorldMatrix) {
  20744. currentMesh.freezeWorldMatrix();
  20745. currentMesh._waitingFreezeWorldMatrix = undefined;
  20746. }
  20747. }
  20748. // Particles
  20749. if (parsedData.particleSystems) {
  20750. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20751. var parsedParticleSystem = parsedData.particleSystems[index];
  20752. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20753. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20754. }
  20755. }
  20756. }
  20757. return true;
  20758. },
  20759. load: function (scene, data, rootUrl) {
  20760. var parsedData = JSON.parse(data);
  20761. // Scene
  20762. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20763. scene.autoClear = parsedData.autoClear;
  20764. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20765. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20766. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20767. // Fog
  20768. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20769. scene.fogMode = parsedData.fogMode;
  20770. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20771. scene.fogStart = parsedData.fogStart;
  20772. scene.fogEnd = parsedData.fogEnd;
  20773. scene.fogDensity = parsedData.fogDensity;
  20774. }
  20775. // Lights
  20776. for (var index = 0; index < parsedData.lights.length; index++) {
  20777. var parsedLight = parsedData.lights[index];
  20778. parseLight(parsedLight, scene);
  20779. }
  20780. // Materials
  20781. if (parsedData.materials) {
  20782. for (index = 0; index < parsedData.materials.length; index++) {
  20783. var parsedMaterial = parsedData.materials[index];
  20784. parseMaterial(parsedMaterial, scene, rootUrl);
  20785. }
  20786. }
  20787. if (parsedData.multiMaterials) {
  20788. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20789. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20790. parseMultiMaterial(parsedMultiMaterial, scene);
  20791. }
  20792. }
  20793. // Skeletons
  20794. if (parsedData.skeletons) {
  20795. for (index = 0; index < parsedData.skeletons.length; index++) {
  20796. var parsedSkeleton = parsedData.skeletons[index];
  20797. parseSkeleton(parsedSkeleton, scene);
  20798. }
  20799. }
  20800. // Geometries
  20801. var geometries = parsedData.geometries;
  20802. if (geometries) {
  20803. // Boxes
  20804. var boxes = geometries.boxes;
  20805. if (boxes) {
  20806. for (index = 0; index < boxes.length; index++) {
  20807. var parsedBox = boxes[index];
  20808. parseBox(parsedBox, scene);
  20809. }
  20810. }
  20811. // Spheres
  20812. var spheres = geometries.spheres;
  20813. if (spheres) {
  20814. for (index = 0; index < spheres.length; index++) {
  20815. var parsedSphere = spheres[index];
  20816. parseSphere(parsedSphere, scene);
  20817. }
  20818. }
  20819. // Cylinders
  20820. var cylinders = geometries.cylinders;
  20821. if (cylinders) {
  20822. for (index = 0; index < cylinders.length; index++) {
  20823. var parsedCylinder = cylinders[index];
  20824. parseCylinder(parsedCylinder, scene);
  20825. }
  20826. }
  20827. // Toruses
  20828. var toruses = geometries.toruses;
  20829. if (toruses) {
  20830. for (index = 0; index < toruses.length; index++) {
  20831. var parsedTorus = toruses[index];
  20832. parseTorus(parsedTorus, scene);
  20833. }
  20834. }
  20835. // Grounds
  20836. var grounds = geometries.grounds;
  20837. if (grounds) {
  20838. for (index = 0; index < grounds.length; index++) {
  20839. var parsedGround = grounds[index];
  20840. parseGround(parsedGround, scene);
  20841. }
  20842. }
  20843. // Planes
  20844. var planes = geometries.planes;
  20845. if (planes) {
  20846. for (index = 0; index < planes.length; index++) {
  20847. var parsedPlane = planes[index];
  20848. parsePlane(parsedPlane, scene);
  20849. }
  20850. }
  20851. // TorusKnots
  20852. var torusKnots = geometries.torusKnots;
  20853. if (torusKnots) {
  20854. for (index = 0; index < torusKnots.length; index++) {
  20855. var parsedTorusKnot = torusKnots[index];
  20856. parseTorusKnot(parsedTorusKnot, scene);
  20857. }
  20858. }
  20859. // VertexData
  20860. var vertexData = geometries.vertexData;
  20861. if (vertexData) {
  20862. for (index = 0; index < vertexData.length; index++) {
  20863. var parsedVertexData = vertexData[index];
  20864. parseVertexData(parsedVertexData, scene, rootUrl);
  20865. }
  20866. }
  20867. }
  20868. // Meshes
  20869. for (index = 0; index < parsedData.meshes.length; index++) {
  20870. var parsedMesh = parsedData.meshes[index];
  20871. parseMesh(parsedMesh, scene, rootUrl);
  20872. }
  20873. // Cameras
  20874. for (index = 0; index < parsedData.cameras.length; index++) {
  20875. var parsedCamera = parsedData.cameras[index];
  20876. parseCamera(parsedCamera, scene);
  20877. }
  20878. if (parsedData.activeCameraID) {
  20879. scene.setActiveCameraByID(parsedData.activeCameraID);
  20880. }
  20881. // Browsing all the graph to connect the dots
  20882. for (index = 0; index < scene.cameras.length; index++) {
  20883. var camera = scene.cameras[index];
  20884. if (camera._waitingParentId) {
  20885. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20886. camera._waitingParentId = undefined;
  20887. }
  20888. }
  20889. for (index = 0; index < scene.lights.length; index++) {
  20890. var light = scene.lights[index];
  20891. if (light._waitingParentId) {
  20892. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20893. light._waitingParentId = undefined;
  20894. }
  20895. }
  20896. // Sounds
  20897. if (parsedData.sounds) {
  20898. for (index = 0; index < parsedData.sounds.length; index++) {
  20899. var parsedSound = parsedData.sounds[index];
  20900. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20901. parseSound(parsedSound, scene, rootUrl);
  20902. }
  20903. else {
  20904. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20905. }
  20906. }
  20907. }
  20908. // Connect parents & children and parse actions
  20909. for (index = 0; index < scene.meshes.length; index++) {
  20910. var mesh = scene.meshes[index];
  20911. if (mesh._waitingParentId) {
  20912. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20913. mesh._waitingParentId = undefined;
  20914. }
  20915. if (mesh._waitingActions) {
  20916. parseActions(mesh._waitingActions, mesh, scene);
  20917. mesh._waitingActions = undefined;
  20918. }
  20919. }
  20920. // freeze world matrix application
  20921. for (index = 0; index < scene.meshes.length; index++) {
  20922. var currentMesh = scene.meshes[index];
  20923. if (currentMesh._waitingFreezeWorldMatrix) {
  20924. currentMesh.freezeWorldMatrix();
  20925. currentMesh._waitingFreezeWorldMatrix = undefined;
  20926. }
  20927. }
  20928. // Particles Systems
  20929. if (parsedData.particleSystems) {
  20930. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20931. var parsedParticleSystem = parsedData.particleSystems[index];
  20932. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20933. }
  20934. }
  20935. // Lens flares
  20936. if (parsedData.lensFlareSystems) {
  20937. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20938. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20939. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20940. }
  20941. }
  20942. // Shadows
  20943. if (parsedData.shadowGenerators) {
  20944. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20945. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20946. parseShadowGenerator(parsedShadowGenerator, scene);
  20947. }
  20948. }
  20949. // Actions (scene)
  20950. if (parsedData.actions) {
  20951. parseActions(parsedData.actions, null, scene);
  20952. }
  20953. // Finish
  20954. return true;
  20955. }
  20956. });
  20957. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20958. })(BABYLON || (BABYLON = {}));
  20959. var BABYLON;
  20960. (function (BABYLON) {
  20961. var SpriteManager = (function () {
  20962. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20964. this.name = name;
  20965. this.cellSize = cellSize;
  20966. this.sprites = new Array();
  20967. this.renderingGroupId = 0;
  20968. this.fogEnabled = true;
  20969. this._vertexDeclaration = [4, 4, 4, 4];
  20970. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20971. this._capacity = capacity;
  20972. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20973. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20974. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20975. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20976. this._scene = scene;
  20977. this._scene.spriteManagers.push(this);
  20978. // VBO
  20979. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20980. var indices = [];
  20981. var index = 0;
  20982. for (var count = 0; count < capacity; count++) {
  20983. indices.push(index);
  20984. indices.push(index + 1);
  20985. indices.push(index + 2);
  20986. indices.push(index);
  20987. indices.push(index + 2);
  20988. indices.push(index + 3);
  20989. index += 4;
  20990. }
  20991. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20992. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20993. // Effects
  20994. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20995. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20996. }
  20997. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20998. var arrayOffset = index * 16;
  20999. if (offsetX === 0)
  21000. offsetX = this._epsilon;
  21001. else if (offsetX === 1)
  21002. offsetX = 1 - this._epsilon;
  21003. if (offsetY === 0)
  21004. offsetY = this._epsilon;
  21005. else if (offsetY === 1)
  21006. offsetY = 1 - this._epsilon;
  21007. this._vertices[arrayOffset] = sprite.position.x;
  21008. this._vertices[arrayOffset + 1] = sprite.position.y;
  21009. this._vertices[arrayOffset + 2] = sprite.position.z;
  21010. this._vertices[arrayOffset + 3] = sprite.angle;
  21011. this._vertices[arrayOffset + 4] = sprite.width;
  21012. this._vertices[arrayOffset + 5] = sprite.height;
  21013. this._vertices[arrayOffset + 6] = offsetX;
  21014. this._vertices[arrayOffset + 7] = offsetY;
  21015. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21016. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21017. var offset = (sprite.cellIndex / rowSize) >> 0;
  21018. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21019. this._vertices[arrayOffset + 11] = offset;
  21020. // Color
  21021. this._vertices[arrayOffset + 12] = sprite.color.r;
  21022. this._vertices[arrayOffset + 13] = sprite.color.g;
  21023. this._vertices[arrayOffset + 14] = sprite.color.b;
  21024. this._vertices[arrayOffset + 15] = sprite.color.a;
  21025. };
  21026. SpriteManager.prototype.render = function () {
  21027. // Check
  21028. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21029. return;
  21030. var engine = this._scene.getEngine();
  21031. var baseSize = this._spriteTexture.getBaseSize();
  21032. // Sprites
  21033. var deltaTime = engine.getDeltaTime();
  21034. var max = Math.min(this._capacity, this.sprites.length);
  21035. var rowSize = baseSize.width / this.cellSize;
  21036. var offset = 0;
  21037. for (var index = 0; index < max; index++) {
  21038. var sprite = this.sprites[index];
  21039. if (!sprite) {
  21040. continue;
  21041. }
  21042. sprite._animate(deltaTime);
  21043. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21044. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21045. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21046. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21047. }
  21048. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21049. // Render
  21050. var effect = this._effectBase;
  21051. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21052. effect = this._effectFog;
  21053. }
  21054. engine.enableEffect(effect);
  21055. var viewMatrix = this._scene.getViewMatrix();
  21056. effect.setTexture("diffuseSampler", this._spriteTexture);
  21057. effect.setMatrix("view", viewMatrix);
  21058. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21059. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21060. // Fog
  21061. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21062. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21063. effect.setColor3("vFogColor", this._scene.fogColor);
  21064. }
  21065. // VBOs
  21066. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21067. // Draw order
  21068. engine.setDepthFunctionToLessOrEqual();
  21069. effect.setBool("alphaTest", true);
  21070. engine.setColorWrite(false);
  21071. engine.draw(true, 0, max * 6);
  21072. engine.setColorWrite(true);
  21073. effect.setBool("alphaTest", false);
  21074. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21075. engine.draw(true, 0, max * 6);
  21076. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21077. };
  21078. SpriteManager.prototype.dispose = function () {
  21079. if (this._vertexBuffer) {
  21080. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21081. this._vertexBuffer = null;
  21082. }
  21083. if (this._indexBuffer) {
  21084. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21085. this._indexBuffer = null;
  21086. }
  21087. if (this._spriteTexture) {
  21088. this._spriteTexture.dispose();
  21089. this._spriteTexture = null;
  21090. }
  21091. // Remove from scene
  21092. var index = this._scene.spriteManagers.indexOf(this);
  21093. this._scene.spriteManagers.splice(index, 1);
  21094. // Callback
  21095. if (this.onDispose) {
  21096. this.onDispose();
  21097. }
  21098. };
  21099. return SpriteManager;
  21100. })();
  21101. BABYLON.SpriteManager = SpriteManager;
  21102. })(BABYLON || (BABYLON = {}));
  21103. var BABYLON;
  21104. (function (BABYLON) {
  21105. var Sprite = (function () {
  21106. function Sprite(name, manager) {
  21107. this.name = name;
  21108. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21109. this.width = 1.0;
  21110. this.height = 1.0;
  21111. this.angle = 0;
  21112. this.cellIndex = 0;
  21113. this.invertU = 0;
  21114. this.invertV = 0;
  21115. this.animations = new Array();
  21116. this._animationStarted = false;
  21117. this._loopAnimation = false;
  21118. this._fromIndex = 0;
  21119. this._toIndex = 0;
  21120. this._delay = 0;
  21121. this._direction = 1;
  21122. this._frameCount = 0;
  21123. this._time = 0;
  21124. this._manager = manager;
  21125. this._manager.sprites.push(this);
  21126. this.position = BABYLON.Vector3.Zero();
  21127. }
  21128. Object.defineProperty(Sprite.prototype, "size", {
  21129. get: function () {
  21130. return this.width;
  21131. },
  21132. set: function (value) {
  21133. this.width = value;
  21134. this.height = value;
  21135. },
  21136. enumerable: true,
  21137. configurable: true
  21138. });
  21139. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21140. this._fromIndex = from;
  21141. this._toIndex = to;
  21142. this._loopAnimation = loop;
  21143. this._delay = delay;
  21144. this._animationStarted = true;
  21145. this._direction = from < to ? 1 : -1;
  21146. this.cellIndex = from;
  21147. this._time = 0;
  21148. };
  21149. Sprite.prototype.stopAnimation = function () {
  21150. this._animationStarted = false;
  21151. };
  21152. Sprite.prototype._animate = function (deltaTime) {
  21153. if (!this._animationStarted)
  21154. return;
  21155. this._time += deltaTime;
  21156. if (this._time > this._delay) {
  21157. this._time = this._time % this._delay;
  21158. this.cellIndex += this._direction;
  21159. if (this.cellIndex == this._toIndex) {
  21160. if (this._loopAnimation) {
  21161. this.cellIndex = this._fromIndex;
  21162. }
  21163. else {
  21164. this._animationStarted = false;
  21165. if (this.disposeWhenFinishedAnimating) {
  21166. this.dispose();
  21167. }
  21168. }
  21169. }
  21170. }
  21171. };
  21172. Sprite.prototype.dispose = function () {
  21173. for (var i = 0; i < this._manager.sprites.length; i++) {
  21174. if (this._manager.sprites[i] == this) {
  21175. this._manager.sprites.splice(i, 1);
  21176. }
  21177. }
  21178. };
  21179. return Sprite;
  21180. })();
  21181. BABYLON.Sprite = Sprite;
  21182. })(BABYLON || (BABYLON = {}));
  21183. var BABYLON;
  21184. (function (BABYLON) {
  21185. var Layer = (function () {
  21186. function Layer(name, imgUrl, scene, isBackground, color) {
  21187. this.name = name;
  21188. this._vertexDeclaration = [2];
  21189. this._vertexStrideSize = 2 * 4;
  21190. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21191. this.isBackground = isBackground === undefined ? true : isBackground;
  21192. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21193. this._scene = scene;
  21194. this._scene.layers.push(this);
  21195. // VBO
  21196. var vertices = [];
  21197. vertices.push(1, 1);
  21198. vertices.push(-1, 1);
  21199. vertices.push(-1, -1);
  21200. vertices.push(1, -1);
  21201. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21202. // Indices
  21203. var indices = [];
  21204. indices.push(0);
  21205. indices.push(1);
  21206. indices.push(2);
  21207. indices.push(0);
  21208. indices.push(2);
  21209. indices.push(3);
  21210. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21211. // Effects
  21212. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21213. }
  21214. Layer.prototype.render = function () {
  21215. // Check
  21216. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21217. return;
  21218. var engine = this._scene.getEngine();
  21219. // Render
  21220. engine.enableEffect(this._effect);
  21221. engine.setState(false);
  21222. // Texture
  21223. this._effect.setTexture("textureSampler", this.texture);
  21224. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21225. // Color
  21226. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21227. // VBOs
  21228. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21229. // Draw order
  21230. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21231. engine.draw(true, 0, 6);
  21232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21233. };
  21234. Layer.prototype.dispose = function () {
  21235. if (this._vertexBuffer) {
  21236. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21237. this._vertexBuffer = null;
  21238. }
  21239. if (this._indexBuffer) {
  21240. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21241. this._indexBuffer = null;
  21242. }
  21243. if (this.texture) {
  21244. this.texture.dispose();
  21245. this.texture = null;
  21246. }
  21247. // Remove from scene
  21248. var index = this._scene.layers.indexOf(this);
  21249. this._scene.layers.splice(index, 1);
  21250. // Callback
  21251. if (this.onDispose) {
  21252. this.onDispose();
  21253. }
  21254. };
  21255. return Layer;
  21256. })();
  21257. BABYLON.Layer = Layer;
  21258. })(BABYLON || (BABYLON = {}));
  21259. var BABYLON;
  21260. (function (BABYLON) {
  21261. var Particle = (function () {
  21262. function Particle() {
  21263. this.position = BABYLON.Vector3.Zero();
  21264. this.direction = BABYLON.Vector3.Zero();
  21265. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21266. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21267. this.lifeTime = 1.0;
  21268. this.age = 0;
  21269. this.size = 0;
  21270. this.angle = 0;
  21271. this.angularSpeed = 0;
  21272. }
  21273. Particle.prototype.copyTo = function (other) {
  21274. other.position.copyFrom(this.position);
  21275. other.direction.copyFrom(this.direction);
  21276. other.color.copyFrom(this.color);
  21277. other.colorStep.copyFrom(this.colorStep);
  21278. other.lifeTime = this.lifeTime;
  21279. other.age = this.age;
  21280. other.size = this.size;
  21281. other.angle = this.angle;
  21282. other.angularSpeed = this.angularSpeed;
  21283. };
  21284. return Particle;
  21285. })();
  21286. BABYLON.Particle = Particle;
  21287. })(BABYLON || (BABYLON = {}));
  21288. var BABYLON;
  21289. (function (BABYLON) {
  21290. var randomNumber = function (min, max) {
  21291. if (min === max) {
  21292. return (min);
  21293. }
  21294. var random = Math.random();
  21295. return ((random * (max - min)) + min);
  21296. };
  21297. var ParticleSystem = (function () {
  21298. function ParticleSystem(name, capacity, scene, customEffect) {
  21299. var _this = this;
  21300. this.name = name;
  21301. this.renderingGroupId = 0;
  21302. this.emitter = null;
  21303. this.emitRate = 10;
  21304. this.manualEmitCount = -1;
  21305. this.updateSpeed = 0.01;
  21306. this.targetStopDuration = 0;
  21307. this.disposeOnStop = false;
  21308. this.minEmitPower = 1;
  21309. this.maxEmitPower = 1;
  21310. this.minLifeTime = 1;
  21311. this.maxLifeTime = 1;
  21312. this.minSize = 1;
  21313. this.maxSize = 1;
  21314. this.minAngularSpeed = 0;
  21315. this.maxAngularSpeed = 0;
  21316. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21317. this.forceDepthWrite = false;
  21318. this.gravity = BABYLON.Vector3.Zero();
  21319. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21320. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21321. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21322. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21323. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21324. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21325. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21326. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21327. this.particles = new Array();
  21328. this._vertexDeclaration = [3, 4, 4];
  21329. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21330. this._stockParticles = new Array();
  21331. this._newPartsExcess = 0;
  21332. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21333. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21334. this._scaledDirection = BABYLON.Vector3.Zero();
  21335. this._scaledGravity = BABYLON.Vector3.Zero();
  21336. this._currentRenderId = -1;
  21337. this._started = false;
  21338. this._stopped = false;
  21339. this._actualFrame = 0;
  21340. this.id = name;
  21341. this._capacity = capacity;
  21342. this._scene = scene;
  21343. this._customEffect = customEffect;
  21344. scene.particleSystems.push(this);
  21345. // VBO
  21346. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21347. var indices = [];
  21348. var index = 0;
  21349. for (var count = 0; count < capacity; count++) {
  21350. indices.push(index);
  21351. indices.push(index + 1);
  21352. indices.push(index + 2);
  21353. indices.push(index);
  21354. indices.push(index + 2);
  21355. indices.push(index + 3);
  21356. index += 4;
  21357. }
  21358. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21359. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21360. // Default behaviors
  21361. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21362. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21363. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21364. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21365. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21366. };
  21367. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21368. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21369. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21370. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21371. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21372. };
  21373. this.updateFunction = function (particles) {
  21374. for (var index = 0; index < particles.length; index++) {
  21375. var particle = particles[index];
  21376. particle.age += _this._scaledUpdateSpeed;
  21377. if (particle.age >= particle.lifeTime) {
  21378. _this.recycleParticle(particle);
  21379. index--;
  21380. continue;
  21381. }
  21382. else {
  21383. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21384. particle.color.addInPlace(_this._scaledColorStep);
  21385. if (particle.color.a < 0)
  21386. particle.color.a = 0;
  21387. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21388. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21389. particle.position.addInPlace(_this._scaledDirection);
  21390. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21391. particle.direction.addInPlace(_this._scaledGravity);
  21392. }
  21393. }
  21394. };
  21395. }
  21396. ParticleSystem.prototype.recycleParticle = function (particle) {
  21397. var lastParticle = this.particles.pop();
  21398. if (lastParticle !== particle) {
  21399. lastParticle.copyTo(particle);
  21400. this._stockParticles.push(lastParticle);
  21401. }
  21402. };
  21403. ParticleSystem.prototype.getCapacity = function () {
  21404. return this._capacity;
  21405. };
  21406. ParticleSystem.prototype.isAlive = function () {
  21407. return this._alive;
  21408. };
  21409. ParticleSystem.prototype.isStarted = function () {
  21410. return this._started;
  21411. };
  21412. ParticleSystem.prototype.start = function () {
  21413. this._started = true;
  21414. this._stopped = false;
  21415. this._actualFrame = 0;
  21416. };
  21417. ParticleSystem.prototype.stop = function () {
  21418. this._stopped = true;
  21419. };
  21420. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21421. var offset = index * 11;
  21422. this._vertices[offset] = particle.position.x;
  21423. this._vertices[offset + 1] = particle.position.y;
  21424. this._vertices[offset + 2] = particle.position.z;
  21425. this._vertices[offset + 3] = particle.color.r;
  21426. this._vertices[offset + 4] = particle.color.g;
  21427. this._vertices[offset + 5] = particle.color.b;
  21428. this._vertices[offset + 6] = particle.color.a;
  21429. this._vertices[offset + 7] = particle.angle;
  21430. this._vertices[offset + 8] = particle.size;
  21431. this._vertices[offset + 9] = offsetX;
  21432. this._vertices[offset + 10] = offsetY;
  21433. };
  21434. ParticleSystem.prototype._update = function (newParticles) {
  21435. // Update current
  21436. this._alive = this.particles.length > 0;
  21437. this.updateFunction(this.particles);
  21438. // Add new ones
  21439. var worldMatrix;
  21440. if (this.emitter.position) {
  21441. worldMatrix = this.emitter.getWorldMatrix();
  21442. }
  21443. else {
  21444. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21445. }
  21446. for (var index = 0; index < newParticles; index++) {
  21447. if (this.particles.length === this._capacity) {
  21448. break;
  21449. }
  21450. if (this._stockParticles.length !== 0) {
  21451. var particle = this._stockParticles.pop();
  21452. particle.age = 0;
  21453. }
  21454. else {
  21455. particle = new BABYLON.Particle();
  21456. }
  21457. this.particles.push(particle);
  21458. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21459. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21460. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21461. particle.size = randomNumber(this.minSize, this.maxSize);
  21462. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21463. this.startPositionFunction(worldMatrix, particle.position);
  21464. var step = randomNumber(0, 1.0);
  21465. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21466. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21467. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21468. }
  21469. };
  21470. ParticleSystem.prototype._getEffect = function () {
  21471. if (this._customEffect) {
  21472. return this._customEffect;
  21473. }
  21474. ;
  21475. var defines = [];
  21476. if (this._scene.clipPlane) {
  21477. defines.push("#define CLIPPLANE");
  21478. }
  21479. // Effect
  21480. var join = defines.join("\n");
  21481. if (this._cachedDefines !== join) {
  21482. this._cachedDefines = join;
  21483. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21484. }
  21485. return this._effect;
  21486. };
  21487. ParticleSystem.prototype.animate = function () {
  21488. if (!this._started)
  21489. return;
  21490. var effect = this._getEffect();
  21491. // Check
  21492. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21493. return;
  21494. if (this._currentRenderId === this._scene.getRenderId()) {
  21495. return;
  21496. }
  21497. this._currentRenderId = this._scene.getRenderId();
  21498. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21499. // determine the number of particles we need to create
  21500. var emitCout;
  21501. if (this.manualEmitCount > -1) {
  21502. emitCout = this.manualEmitCount;
  21503. this.manualEmitCount = 0;
  21504. }
  21505. else {
  21506. emitCout = this.emitRate;
  21507. }
  21508. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21509. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21510. if (this._newPartsExcess > 1.0) {
  21511. newParticles += this._newPartsExcess >> 0;
  21512. this._newPartsExcess -= this._newPartsExcess >> 0;
  21513. }
  21514. this._alive = false;
  21515. if (!this._stopped) {
  21516. this._actualFrame += this._scaledUpdateSpeed;
  21517. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21518. this.stop();
  21519. }
  21520. else {
  21521. newParticles = 0;
  21522. }
  21523. this._update(newParticles);
  21524. // Stopped?
  21525. if (this._stopped) {
  21526. if (!this._alive) {
  21527. this._started = false;
  21528. if (this.disposeOnStop) {
  21529. this._scene._toBeDisposed.push(this);
  21530. }
  21531. }
  21532. }
  21533. // Update VBO
  21534. var offset = 0;
  21535. for (var index = 0; index < this.particles.length; index++) {
  21536. var particle = this.particles[index];
  21537. this._appendParticleVertex(offset++, particle, 0, 0);
  21538. this._appendParticleVertex(offset++, particle, 1, 0);
  21539. this._appendParticleVertex(offset++, particle, 1, 1);
  21540. this._appendParticleVertex(offset++, particle, 0, 1);
  21541. }
  21542. var engine = this._scene.getEngine();
  21543. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21544. };
  21545. ParticleSystem.prototype.render = function () {
  21546. var effect = this._getEffect();
  21547. // Check
  21548. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21549. return 0;
  21550. var engine = this._scene.getEngine();
  21551. // Render
  21552. engine.enableEffect(effect);
  21553. engine.setState(false);
  21554. var viewMatrix = this._scene.getViewMatrix();
  21555. effect.setTexture("diffuseSampler", this.particleTexture);
  21556. effect.setMatrix("view", viewMatrix);
  21557. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21558. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21559. if (this._scene.clipPlane) {
  21560. var clipPlane = this._scene.clipPlane;
  21561. var invView = viewMatrix.clone();
  21562. invView.invert();
  21563. effect.setMatrix("invView", invView);
  21564. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21565. }
  21566. // VBOs
  21567. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21568. // Draw order
  21569. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21570. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21571. }
  21572. else {
  21573. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21574. }
  21575. if (this.forceDepthWrite) {
  21576. engine.setDepthWrite(true);
  21577. }
  21578. engine.draw(true, 0, this.particles.length * 6);
  21579. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21580. return this.particles.length;
  21581. };
  21582. ParticleSystem.prototype.dispose = function () {
  21583. if (this._vertexBuffer) {
  21584. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21585. this._vertexBuffer = null;
  21586. }
  21587. if (this._indexBuffer) {
  21588. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21589. this._indexBuffer = null;
  21590. }
  21591. if (this.particleTexture) {
  21592. this.particleTexture.dispose();
  21593. this.particleTexture = null;
  21594. }
  21595. // Remove from scene
  21596. var index = this._scene.particleSystems.indexOf(this);
  21597. this._scene.particleSystems.splice(index, 1);
  21598. // Callback
  21599. if (this.onDispose) {
  21600. this.onDispose();
  21601. }
  21602. };
  21603. // Clone
  21604. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21605. var result = new ParticleSystem(name, this._capacity, this._scene);
  21606. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21607. if (newEmitter === undefined) {
  21608. newEmitter = this.emitter;
  21609. }
  21610. result.emitter = newEmitter;
  21611. if (this.particleTexture) {
  21612. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21613. }
  21614. result.start();
  21615. return result;
  21616. };
  21617. // Statics
  21618. ParticleSystem.BLENDMODE_ONEONE = 0;
  21619. ParticleSystem.BLENDMODE_STANDARD = 1;
  21620. return ParticleSystem;
  21621. })();
  21622. BABYLON.ParticleSystem = ParticleSystem;
  21623. })(BABYLON || (BABYLON = {}));
  21624. var BABYLON;
  21625. (function (BABYLON) {
  21626. var Animation = (function () {
  21627. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21628. this.name = name;
  21629. this.targetProperty = targetProperty;
  21630. this.framePerSecond = framePerSecond;
  21631. this.dataType = dataType;
  21632. this.loopMode = loopMode;
  21633. this._offsetsCache = {};
  21634. this._highLimitsCache = {};
  21635. this._stopped = false;
  21636. this.allowMatricesInterpolation = false;
  21637. this.targetPropertyPath = targetProperty.split(".");
  21638. this.dataType = dataType;
  21639. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21640. }
  21641. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21642. var dataType = undefined;
  21643. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21644. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21645. }
  21646. else if (from instanceof BABYLON.Quaternion) {
  21647. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21648. }
  21649. else if (from instanceof BABYLON.Vector3) {
  21650. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21651. }
  21652. else if (from instanceof BABYLON.Vector2) {
  21653. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21654. }
  21655. else if (from instanceof BABYLON.Color3) {
  21656. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21657. }
  21658. if (dataType == undefined) {
  21659. return null;
  21660. }
  21661. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21662. var keys = [];
  21663. keys.push({ frame: 0, value: from });
  21664. keys.push({ frame: totalFrame, value: to });
  21665. animation.setKeys(keys);
  21666. if (easingFunction !== undefined) {
  21667. animation.setEasingFunction(easingFunction);
  21668. }
  21669. mesh.animations.push(animation);
  21670. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21671. };
  21672. // Methods
  21673. Animation.prototype.reset = function () {
  21674. this._offsetsCache = {};
  21675. this._highLimitsCache = {};
  21676. this.currentFrame = 0;
  21677. };
  21678. Animation.prototype.isStopped = function () {
  21679. return this._stopped;
  21680. };
  21681. Animation.prototype.getKeys = function () {
  21682. return this._keys;
  21683. };
  21684. Animation.prototype.getEasingFunction = function () {
  21685. return this._easingFunction;
  21686. };
  21687. Animation.prototype.setEasingFunction = function (easingFunction) {
  21688. this._easingFunction = easingFunction;
  21689. };
  21690. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21691. return startValue + (endValue - startValue) * gradient;
  21692. };
  21693. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21694. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21695. };
  21696. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21697. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21698. };
  21699. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21700. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21701. };
  21702. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21703. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21704. };
  21705. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21706. var startScale = new BABYLON.Vector3(0, 0, 0);
  21707. var startRotation = new BABYLON.Quaternion();
  21708. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21709. startValue.decompose(startScale, startRotation, startTranslation);
  21710. var endScale = new BABYLON.Vector3(0, 0, 0);
  21711. var endRotation = new BABYLON.Quaternion();
  21712. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21713. endValue.decompose(endScale, endRotation, endTranslation);
  21714. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21715. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21716. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21717. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21718. return result;
  21719. };
  21720. Animation.prototype.clone = function () {
  21721. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21722. clone.setKeys(this._keys);
  21723. return clone;
  21724. };
  21725. Animation.prototype.setKeys = function (values) {
  21726. this._keys = values.slice(0);
  21727. this._offsetsCache = {};
  21728. this._highLimitsCache = {};
  21729. };
  21730. Animation.prototype._getKeyValue = function (value) {
  21731. if (typeof value === "function") {
  21732. return value();
  21733. }
  21734. return value;
  21735. };
  21736. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21737. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21738. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21739. }
  21740. this.currentFrame = currentFrame;
  21741. // Try to get a hash to find the right key
  21742. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  21743. if (this._keys[startKey].frame >= currentFrame) {
  21744. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21745. startKey--;
  21746. }
  21747. }
  21748. for (var key = startKey; key < this._keys.length; key++) {
  21749. if (this._keys[key + 1].frame >= currentFrame) {
  21750. var startValue = this._getKeyValue(this._keys[key].value);
  21751. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21752. // gradient : percent of currentFrame between the frame inf and the frame sup
  21753. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21754. // check for easingFunction and correction of gradient
  21755. if (this._easingFunction != null) {
  21756. gradient = this._easingFunction.ease(gradient);
  21757. }
  21758. switch (this.dataType) {
  21759. // Float
  21760. case Animation.ANIMATIONTYPE_FLOAT:
  21761. switch (loopMode) {
  21762. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21763. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21764. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21765. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21766. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21767. }
  21768. break;
  21769. // Quaternion
  21770. case Animation.ANIMATIONTYPE_QUATERNION:
  21771. var quaternion = null;
  21772. switch (loopMode) {
  21773. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21774. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21775. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21776. break;
  21777. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21778. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21779. break;
  21780. }
  21781. return quaternion;
  21782. // Vector3
  21783. case Animation.ANIMATIONTYPE_VECTOR3:
  21784. switch (loopMode) {
  21785. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21786. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21787. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21788. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21789. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21790. }
  21791. // Vector2
  21792. case Animation.ANIMATIONTYPE_VECTOR2:
  21793. switch (loopMode) {
  21794. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21795. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21796. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21797. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21798. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21799. }
  21800. // Color3
  21801. case Animation.ANIMATIONTYPE_COLOR3:
  21802. switch (loopMode) {
  21803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21805. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21807. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21808. }
  21809. // Matrix
  21810. case Animation.ANIMATIONTYPE_MATRIX:
  21811. switch (loopMode) {
  21812. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21813. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21814. if (this.allowMatricesInterpolation) {
  21815. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21816. }
  21817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21818. return startValue;
  21819. }
  21820. default:
  21821. break;
  21822. }
  21823. break;
  21824. }
  21825. }
  21826. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21827. };
  21828. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21829. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21830. this._stopped = true;
  21831. return false;
  21832. }
  21833. var returnValue = true;
  21834. // Adding a start key at frame 0 if missing
  21835. if (this._keys[0].frame !== 0) {
  21836. var newKey = { frame: 0, value: this._keys[0].value };
  21837. this._keys.splice(0, 0, newKey);
  21838. }
  21839. // Check limits
  21840. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21841. from = this._keys[0].frame;
  21842. }
  21843. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21844. to = this._keys[this._keys.length - 1].frame;
  21845. }
  21846. // Compute ratio
  21847. var range = to - from;
  21848. var offsetValue;
  21849. // ratio represents the frame delta between from and to
  21850. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21851. var highLimitValue = 0;
  21852. if (ratio > range && !loop) {
  21853. returnValue = false;
  21854. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21855. }
  21856. else {
  21857. // Get max value if required
  21858. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21859. var keyOffset = to.toString() + from.toString();
  21860. if (!this._offsetsCache[keyOffset]) {
  21861. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21862. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21863. switch (this.dataType) {
  21864. // Float
  21865. case Animation.ANIMATIONTYPE_FLOAT:
  21866. this._offsetsCache[keyOffset] = toValue - fromValue;
  21867. break;
  21868. // Quaternion
  21869. case Animation.ANIMATIONTYPE_QUATERNION:
  21870. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21871. break;
  21872. // Vector3
  21873. case Animation.ANIMATIONTYPE_VECTOR3:
  21874. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21875. // Vector2
  21876. case Animation.ANIMATIONTYPE_VECTOR2:
  21877. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21878. // Color3
  21879. case Animation.ANIMATIONTYPE_COLOR3:
  21880. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21881. default:
  21882. break;
  21883. }
  21884. this._highLimitsCache[keyOffset] = toValue;
  21885. }
  21886. highLimitValue = this._highLimitsCache[keyOffset];
  21887. offsetValue = this._offsetsCache[keyOffset];
  21888. }
  21889. }
  21890. if (offsetValue === undefined) {
  21891. switch (this.dataType) {
  21892. // Float
  21893. case Animation.ANIMATIONTYPE_FLOAT:
  21894. offsetValue = 0;
  21895. break;
  21896. // Quaternion
  21897. case Animation.ANIMATIONTYPE_QUATERNION:
  21898. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21899. break;
  21900. // Vector3
  21901. case Animation.ANIMATIONTYPE_VECTOR3:
  21902. offsetValue = BABYLON.Vector3.Zero();
  21903. break;
  21904. // Vector2
  21905. case Animation.ANIMATIONTYPE_VECTOR2:
  21906. offsetValue = BABYLON.Vector2.Zero();
  21907. break;
  21908. // Color3
  21909. case Animation.ANIMATIONTYPE_COLOR3:
  21910. offsetValue = BABYLON.Color3.Black();
  21911. }
  21912. }
  21913. // Compute value
  21914. var repeatCount = (ratio / range) >> 0;
  21915. var currentFrame = returnValue ? from + ratio % range : to;
  21916. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21917. // Set value
  21918. if (this.targetPropertyPath.length > 1) {
  21919. var property = this._target[this.targetPropertyPath[0]];
  21920. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21921. property = property[this.targetPropertyPath[index]];
  21922. }
  21923. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21924. }
  21925. else {
  21926. this._target[this.targetPropertyPath[0]] = currentValue;
  21927. }
  21928. if (this._target.markAsDirty) {
  21929. this._target.markAsDirty(this.targetProperty);
  21930. }
  21931. if (!returnValue) {
  21932. this._stopped = true;
  21933. }
  21934. return returnValue;
  21935. };
  21936. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21937. get: function () {
  21938. return Animation._ANIMATIONTYPE_FLOAT;
  21939. },
  21940. enumerable: true,
  21941. configurable: true
  21942. });
  21943. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21944. get: function () {
  21945. return Animation._ANIMATIONTYPE_VECTOR3;
  21946. },
  21947. enumerable: true,
  21948. configurable: true
  21949. });
  21950. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21951. get: function () {
  21952. return Animation._ANIMATIONTYPE_VECTOR2;
  21953. },
  21954. enumerable: true,
  21955. configurable: true
  21956. });
  21957. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21958. get: function () {
  21959. return Animation._ANIMATIONTYPE_QUATERNION;
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21965. get: function () {
  21966. return Animation._ANIMATIONTYPE_MATRIX;
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21972. get: function () {
  21973. return Animation._ANIMATIONTYPE_COLOR3;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21979. get: function () {
  21980. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21986. get: function () {
  21987. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21993. get: function () {
  21994. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. // Statics
  22000. Animation._ANIMATIONTYPE_FLOAT = 0;
  22001. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22002. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22003. Animation._ANIMATIONTYPE_MATRIX = 3;
  22004. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22005. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22006. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22007. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22008. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22009. return Animation;
  22010. })();
  22011. BABYLON.Animation = Animation;
  22012. })(BABYLON || (BABYLON = {}));
  22013. var BABYLON;
  22014. (function (BABYLON) {
  22015. var Animatable = (function () {
  22016. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22017. if (fromFrame === void 0) { fromFrame = 0; }
  22018. if (toFrame === void 0) { toFrame = 100; }
  22019. if (loopAnimation === void 0) { loopAnimation = false; }
  22020. if (speedRatio === void 0) { speedRatio = 1.0; }
  22021. this.target = target;
  22022. this.fromFrame = fromFrame;
  22023. this.toFrame = toFrame;
  22024. this.loopAnimation = loopAnimation;
  22025. this.speedRatio = speedRatio;
  22026. this.onAnimationEnd = onAnimationEnd;
  22027. this._animations = new Array();
  22028. this._paused = false;
  22029. this.animationStarted = false;
  22030. if (animations) {
  22031. this.appendAnimations(target, animations);
  22032. }
  22033. this._scene = scene;
  22034. scene._activeAnimatables.push(this);
  22035. }
  22036. // Methods
  22037. Animatable.prototype.appendAnimations = function (target, animations) {
  22038. for (var index = 0; index < animations.length; index++) {
  22039. var animation = animations[index];
  22040. animation._target = target;
  22041. this._animations.push(animation);
  22042. }
  22043. };
  22044. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22045. var animations = this._animations;
  22046. for (var index = 0; index < animations.length; index++) {
  22047. if (animations[index].targetProperty === property) {
  22048. return animations[index];
  22049. }
  22050. }
  22051. return null;
  22052. };
  22053. Animatable.prototype.reset = function () {
  22054. var animations = this._animations;
  22055. for (var index = 0; index < animations.length; index++) {
  22056. animations[index].reset();
  22057. }
  22058. this._localDelayOffset = null;
  22059. this._pausedDelay = null;
  22060. };
  22061. Animatable.prototype.pause = function () {
  22062. if (this._paused) {
  22063. return;
  22064. }
  22065. this._paused = true;
  22066. };
  22067. Animatable.prototype.restart = function () {
  22068. this._paused = false;
  22069. };
  22070. Animatable.prototype.stop = function () {
  22071. var index = this._scene._activeAnimatables.indexOf(this);
  22072. if (index > -1) {
  22073. this._scene._activeAnimatables.splice(index, 1);
  22074. }
  22075. if (this.onAnimationEnd) {
  22076. this.onAnimationEnd();
  22077. }
  22078. };
  22079. Animatable.prototype._animate = function (delay) {
  22080. if (this._paused) {
  22081. if (!this._pausedDelay) {
  22082. this._pausedDelay = delay;
  22083. }
  22084. return true;
  22085. }
  22086. if (!this._localDelayOffset) {
  22087. this._localDelayOffset = delay;
  22088. }
  22089. else if (this._pausedDelay) {
  22090. this._localDelayOffset += delay - this._pausedDelay;
  22091. this._pausedDelay = null;
  22092. }
  22093. // Animating
  22094. var running = false;
  22095. var animations = this._animations;
  22096. for (var index = 0; index < animations.length; index++) {
  22097. var animation = animations[index];
  22098. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22099. running = running || isRunning;
  22100. }
  22101. if (!running) {
  22102. // Remove from active animatables
  22103. index = this._scene._activeAnimatables.indexOf(this);
  22104. this._scene._activeAnimatables.splice(index, 1);
  22105. }
  22106. if (!running && this.onAnimationEnd) {
  22107. this.onAnimationEnd();
  22108. }
  22109. return running;
  22110. };
  22111. return Animatable;
  22112. })();
  22113. BABYLON.Animatable = Animatable;
  22114. })(BABYLON || (BABYLON = {}));
  22115. var BABYLON;
  22116. (function (BABYLON) {
  22117. var EasingFunction = (function () {
  22118. function EasingFunction() {
  22119. // Properties
  22120. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22121. }
  22122. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22123. get: function () {
  22124. return EasingFunction._EASINGMODE_EASEIN;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22130. get: function () {
  22131. return EasingFunction._EASINGMODE_EASEOUT;
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22137. get: function () {
  22138. return EasingFunction._EASINGMODE_EASEINOUT;
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22144. var n = Math.min(Math.max(easingMode, 0), 2);
  22145. this._easingMode = n;
  22146. };
  22147. EasingFunction.prototype.getEasingMode = function () {
  22148. return this._easingMode;
  22149. };
  22150. EasingFunction.prototype.easeInCore = function (gradient) {
  22151. throw new Error('You must implement this method');
  22152. };
  22153. EasingFunction.prototype.ease = function (gradient) {
  22154. switch (this._easingMode) {
  22155. case EasingFunction.EASINGMODE_EASEIN:
  22156. return this.easeInCore(gradient);
  22157. case EasingFunction.EASINGMODE_EASEOUT:
  22158. return (1 - this.easeInCore(1 - gradient));
  22159. }
  22160. if (gradient >= 0.5) {
  22161. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22162. }
  22163. return (this.easeInCore(gradient * 2) * 0.5);
  22164. };
  22165. //Statics
  22166. EasingFunction._EASINGMODE_EASEIN = 0;
  22167. EasingFunction._EASINGMODE_EASEOUT = 1;
  22168. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22169. return EasingFunction;
  22170. })();
  22171. BABYLON.EasingFunction = EasingFunction;
  22172. var CircleEase = (function (_super) {
  22173. __extends(CircleEase, _super);
  22174. function CircleEase() {
  22175. _super.apply(this, arguments);
  22176. }
  22177. CircleEase.prototype.easeInCore = function (gradient) {
  22178. gradient = Math.max(0, Math.min(1, gradient));
  22179. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22180. };
  22181. return CircleEase;
  22182. })(EasingFunction);
  22183. BABYLON.CircleEase = CircleEase;
  22184. var BackEase = (function (_super) {
  22185. __extends(BackEase, _super);
  22186. function BackEase(amplitude) {
  22187. if (amplitude === void 0) { amplitude = 1; }
  22188. _super.call(this);
  22189. this.amplitude = amplitude;
  22190. }
  22191. BackEase.prototype.easeInCore = function (gradient) {
  22192. var num = Math.max(0, this.amplitude);
  22193. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22194. };
  22195. return BackEase;
  22196. })(EasingFunction);
  22197. BABYLON.BackEase = BackEase;
  22198. var BounceEase = (function (_super) {
  22199. __extends(BounceEase, _super);
  22200. function BounceEase(bounces, bounciness) {
  22201. if (bounces === void 0) { bounces = 3; }
  22202. if (bounciness === void 0) { bounciness = 2; }
  22203. _super.call(this);
  22204. this.bounces = bounces;
  22205. this.bounciness = bounciness;
  22206. }
  22207. BounceEase.prototype.easeInCore = function (gradient) {
  22208. var y = Math.max(0.0, this.bounces);
  22209. var bounciness = this.bounciness;
  22210. if (bounciness <= 1.0) {
  22211. bounciness = 1.001;
  22212. }
  22213. var num9 = Math.pow(bounciness, y);
  22214. var num5 = 1.0 - bounciness;
  22215. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22216. var num15 = gradient * num4;
  22217. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22218. var num3 = Math.floor(num65);
  22219. var num13 = num3 + 1.0;
  22220. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22221. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22222. var num7 = (num8 + num12) * 0.5;
  22223. var num6 = gradient - num7;
  22224. var num2 = num7 - num8;
  22225. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22226. };
  22227. return BounceEase;
  22228. })(EasingFunction);
  22229. BABYLON.BounceEase = BounceEase;
  22230. var CubicEase = (function (_super) {
  22231. __extends(CubicEase, _super);
  22232. function CubicEase() {
  22233. _super.apply(this, arguments);
  22234. }
  22235. CubicEase.prototype.easeInCore = function (gradient) {
  22236. return (gradient * gradient * gradient);
  22237. };
  22238. return CubicEase;
  22239. })(EasingFunction);
  22240. BABYLON.CubicEase = CubicEase;
  22241. var ElasticEase = (function (_super) {
  22242. __extends(ElasticEase, _super);
  22243. function ElasticEase(oscillations, springiness) {
  22244. if (oscillations === void 0) { oscillations = 3; }
  22245. if (springiness === void 0) { springiness = 3; }
  22246. _super.call(this);
  22247. this.oscillations = oscillations;
  22248. this.springiness = springiness;
  22249. }
  22250. ElasticEase.prototype.easeInCore = function (gradient) {
  22251. var num2;
  22252. var num3 = Math.max(0.0, this.oscillations);
  22253. var num = Math.max(0.0, this.springiness);
  22254. if (num == 0) {
  22255. num2 = gradient;
  22256. }
  22257. else {
  22258. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22259. }
  22260. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22261. };
  22262. return ElasticEase;
  22263. })(EasingFunction);
  22264. BABYLON.ElasticEase = ElasticEase;
  22265. var ExponentialEase = (function (_super) {
  22266. __extends(ExponentialEase, _super);
  22267. function ExponentialEase(exponent) {
  22268. if (exponent === void 0) { exponent = 2; }
  22269. _super.call(this);
  22270. this.exponent = exponent;
  22271. }
  22272. ExponentialEase.prototype.easeInCore = function (gradient) {
  22273. if (this.exponent <= 0) {
  22274. return gradient;
  22275. }
  22276. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22277. };
  22278. return ExponentialEase;
  22279. })(EasingFunction);
  22280. BABYLON.ExponentialEase = ExponentialEase;
  22281. var PowerEase = (function (_super) {
  22282. __extends(PowerEase, _super);
  22283. function PowerEase(power) {
  22284. if (power === void 0) { power = 2; }
  22285. _super.call(this);
  22286. this.power = power;
  22287. }
  22288. PowerEase.prototype.easeInCore = function (gradient) {
  22289. var y = Math.max(0.0, this.power);
  22290. return Math.pow(gradient, y);
  22291. };
  22292. return PowerEase;
  22293. })(EasingFunction);
  22294. BABYLON.PowerEase = PowerEase;
  22295. var QuadraticEase = (function (_super) {
  22296. __extends(QuadraticEase, _super);
  22297. function QuadraticEase() {
  22298. _super.apply(this, arguments);
  22299. }
  22300. QuadraticEase.prototype.easeInCore = function (gradient) {
  22301. return (gradient * gradient);
  22302. };
  22303. return QuadraticEase;
  22304. })(EasingFunction);
  22305. BABYLON.QuadraticEase = QuadraticEase;
  22306. var QuarticEase = (function (_super) {
  22307. __extends(QuarticEase, _super);
  22308. function QuarticEase() {
  22309. _super.apply(this, arguments);
  22310. }
  22311. QuarticEase.prototype.easeInCore = function (gradient) {
  22312. return (gradient * gradient * gradient * gradient);
  22313. };
  22314. return QuarticEase;
  22315. })(EasingFunction);
  22316. BABYLON.QuarticEase = QuarticEase;
  22317. var QuinticEase = (function (_super) {
  22318. __extends(QuinticEase, _super);
  22319. function QuinticEase() {
  22320. _super.apply(this, arguments);
  22321. }
  22322. QuinticEase.prototype.easeInCore = function (gradient) {
  22323. return (gradient * gradient * gradient * gradient * gradient);
  22324. };
  22325. return QuinticEase;
  22326. })(EasingFunction);
  22327. BABYLON.QuinticEase = QuinticEase;
  22328. var SineEase = (function (_super) {
  22329. __extends(SineEase, _super);
  22330. function SineEase() {
  22331. _super.apply(this, arguments);
  22332. }
  22333. SineEase.prototype.easeInCore = function (gradient) {
  22334. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22335. };
  22336. return SineEase;
  22337. })(EasingFunction);
  22338. BABYLON.SineEase = SineEase;
  22339. var BezierCurveEase = (function (_super) {
  22340. __extends(BezierCurveEase, _super);
  22341. function BezierCurveEase(x1, y1, x2, y2) {
  22342. if (x1 === void 0) { x1 = 0; }
  22343. if (y1 === void 0) { y1 = 0; }
  22344. if (x2 === void 0) { x2 = 1; }
  22345. if (y2 === void 0) { y2 = 1; }
  22346. _super.call(this);
  22347. this.x1 = x1;
  22348. this.y1 = y1;
  22349. this.x2 = x2;
  22350. this.y2 = y2;
  22351. }
  22352. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22353. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22354. };
  22355. return BezierCurveEase;
  22356. })(EasingFunction);
  22357. BABYLON.BezierCurveEase = BezierCurveEase;
  22358. })(BABYLON || (BABYLON = {}));
  22359. var BABYLON;
  22360. (function (BABYLON) {
  22361. var Octree = (function () {
  22362. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22363. if (maxDepth === void 0) { maxDepth = 2; }
  22364. this.maxDepth = maxDepth;
  22365. this.dynamicContent = new Array();
  22366. this._maxBlockCapacity = maxBlockCapacity || 64;
  22367. this._selectionContent = new BABYLON.SmartArray(1024);
  22368. this._creationFunc = creationFunc;
  22369. }
  22370. // Methods
  22371. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22372. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22373. };
  22374. Octree.prototype.addMesh = function (entry) {
  22375. for (var index = 0; index < this.blocks.length; index++) {
  22376. var block = this.blocks[index];
  22377. block.addEntry(entry);
  22378. }
  22379. };
  22380. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22381. this._selectionContent.reset();
  22382. for (var index = 0; index < this.blocks.length; index++) {
  22383. var block = this.blocks[index];
  22384. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22385. }
  22386. if (allowDuplicate) {
  22387. this._selectionContent.concat(this.dynamicContent);
  22388. }
  22389. else {
  22390. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22391. }
  22392. return this._selectionContent;
  22393. };
  22394. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22395. this._selectionContent.reset();
  22396. for (var index = 0; index < this.blocks.length; index++) {
  22397. var block = this.blocks[index];
  22398. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22399. }
  22400. if (allowDuplicate) {
  22401. this._selectionContent.concat(this.dynamicContent);
  22402. }
  22403. else {
  22404. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22405. }
  22406. return this._selectionContent;
  22407. };
  22408. Octree.prototype.intersectsRay = function (ray) {
  22409. this._selectionContent.reset();
  22410. for (var index = 0; index < this.blocks.length; index++) {
  22411. var block = this.blocks[index];
  22412. block.intersectsRay(ray, this._selectionContent);
  22413. }
  22414. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22415. return this._selectionContent;
  22416. };
  22417. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22418. target.blocks = new Array();
  22419. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22420. // Segmenting space
  22421. for (var x = 0; x < 2; x++) {
  22422. for (var y = 0; y < 2; y++) {
  22423. for (var z = 0; z < 2; z++) {
  22424. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22425. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22426. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22427. block.addEntries(entries);
  22428. target.blocks.push(block);
  22429. }
  22430. }
  22431. }
  22432. };
  22433. Octree.CreationFuncForMeshes = function (entry, block) {
  22434. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22435. block.entries.push(entry);
  22436. }
  22437. };
  22438. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22439. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22440. block.entries.push(entry);
  22441. }
  22442. };
  22443. return Octree;
  22444. })();
  22445. BABYLON.Octree = Octree;
  22446. })(BABYLON || (BABYLON = {}));
  22447. var BABYLON;
  22448. (function (BABYLON) {
  22449. var OctreeBlock = (function () {
  22450. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22451. this.entries = new Array();
  22452. this._boundingVectors = new Array();
  22453. this._capacity = capacity;
  22454. this._depth = depth;
  22455. this._maxDepth = maxDepth;
  22456. this._creationFunc = creationFunc;
  22457. this._minPoint = minPoint;
  22458. this._maxPoint = maxPoint;
  22459. this._boundingVectors.push(minPoint.clone());
  22460. this._boundingVectors.push(maxPoint.clone());
  22461. this._boundingVectors.push(minPoint.clone());
  22462. this._boundingVectors[2].x = maxPoint.x;
  22463. this._boundingVectors.push(minPoint.clone());
  22464. this._boundingVectors[3].y = maxPoint.y;
  22465. this._boundingVectors.push(minPoint.clone());
  22466. this._boundingVectors[4].z = maxPoint.z;
  22467. this._boundingVectors.push(maxPoint.clone());
  22468. this._boundingVectors[5].z = minPoint.z;
  22469. this._boundingVectors.push(maxPoint.clone());
  22470. this._boundingVectors[6].x = minPoint.x;
  22471. this._boundingVectors.push(maxPoint.clone());
  22472. this._boundingVectors[7].y = minPoint.y;
  22473. }
  22474. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22475. // Property
  22476. get: function () {
  22477. return this._capacity;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22483. get: function () {
  22484. return this._minPoint;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22490. get: function () {
  22491. return this._maxPoint;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. // Methods
  22497. OctreeBlock.prototype.addEntry = function (entry) {
  22498. if (this.blocks) {
  22499. for (var index = 0; index < this.blocks.length; index++) {
  22500. var block = this.blocks[index];
  22501. block.addEntry(entry);
  22502. }
  22503. return;
  22504. }
  22505. this._creationFunc(entry, this);
  22506. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22507. this.createInnerBlocks();
  22508. }
  22509. };
  22510. OctreeBlock.prototype.addEntries = function (entries) {
  22511. for (var index = 0; index < entries.length; index++) {
  22512. var mesh = entries[index];
  22513. this.addEntry(mesh);
  22514. }
  22515. };
  22516. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22517. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22518. if (this.blocks) {
  22519. for (var index = 0; index < this.blocks.length; index++) {
  22520. var block = this.blocks[index];
  22521. block.select(frustumPlanes, selection, allowDuplicate);
  22522. }
  22523. return;
  22524. }
  22525. if (allowDuplicate) {
  22526. selection.concat(this.entries);
  22527. }
  22528. else {
  22529. selection.concatWithNoDuplicate(this.entries);
  22530. }
  22531. }
  22532. };
  22533. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22534. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22535. if (this.blocks) {
  22536. for (var index = 0; index < this.blocks.length; index++) {
  22537. var block = this.blocks[index];
  22538. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22539. }
  22540. return;
  22541. }
  22542. if (allowDuplicate) {
  22543. selection.concat(this.entries);
  22544. }
  22545. else {
  22546. selection.concatWithNoDuplicate(this.entries);
  22547. }
  22548. }
  22549. };
  22550. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22551. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22552. if (this.blocks) {
  22553. for (var index = 0; index < this.blocks.length; index++) {
  22554. var block = this.blocks[index];
  22555. block.intersectsRay(ray, selection);
  22556. }
  22557. return;
  22558. }
  22559. selection.concatWithNoDuplicate(this.entries);
  22560. }
  22561. };
  22562. OctreeBlock.prototype.createInnerBlocks = function () {
  22563. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22564. };
  22565. return OctreeBlock;
  22566. })();
  22567. BABYLON.OctreeBlock = OctreeBlock;
  22568. })(BABYLON || (BABYLON = {}));
  22569. var BABYLON;
  22570. (function (BABYLON) {
  22571. var Bone = (function (_super) {
  22572. __extends(Bone, _super);
  22573. function Bone(name, skeleton, parentBone, matrix) {
  22574. _super.call(this, name, skeleton.getScene());
  22575. this.name = name;
  22576. this.children = new Array();
  22577. this.animations = new Array();
  22578. this._worldTransform = new BABYLON.Matrix();
  22579. this._absoluteTransform = new BABYLON.Matrix();
  22580. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22581. this._skeleton = skeleton;
  22582. this._matrix = matrix;
  22583. this._baseMatrix = matrix;
  22584. skeleton.bones.push(this);
  22585. if (parentBone) {
  22586. this._parent = parentBone;
  22587. parentBone.children.push(this);
  22588. }
  22589. else {
  22590. this._parent = null;
  22591. }
  22592. this._updateDifferenceMatrix();
  22593. }
  22594. // Members
  22595. Bone.prototype.getParent = function () {
  22596. return this._parent;
  22597. };
  22598. Bone.prototype.getLocalMatrix = function () {
  22599. return this._matrix;
  22600. };
  22601. Bone.prototype.getBaseMatrix = function () {
  22602. return this._baseMatrix;
  22603. };
  22604. Bone.prototype.getWorldMatrix = function () {
  22605. return this._worldTransform;
  22606. };
  22607. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22608. return this._invertedAbsoluteTransform;
  22609. };
  22610. Bone.prototype.getAbsoluteMatrix = function () {
  22611. var matrix = this._matrix.clone();
  22612. var parent = this._parent;
  22613. while (parent) {
  22614. matrix = matrix.multiply(parent.getLocalMatrix());
  22615. parent = parent.getParent();
  22616. }
  22617. return matrix;
  22618. };
  22619. // Methods
  22620. Bone.prototype.updateMatrix = function (matrix) {
  22621. this._matrix = matrix;
  22622. this._skeleton._markAsDirty();
  22623. this._updateDifferenceMatrix();
  22624. };
  22625. Bone.prototype._updateDifferenceMatrix = function () {
  22626. if (this._parent) {
  22627. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22628. }
  22629. else {
  22630. this._absoluteTransform.copyFrom(this._matrix);
  22631. }
  22632. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22633. for (var index = 0; index < this.children.length; index++) {
  22634. this.children[index]._updateDifferenceMatrix();
  22635. }
  22636. };
  22637. Bone.prototype.markAsDirty = function () {
  22638. this._currentRenderId++;
  22639. this._skeleton._markAsDirty();
  22640. };
  22641. return Bone;
  22642. })(BABYLON.Node);
  22643. BABYLON.Bone = Bone;
  22644. })(BABYLON || (BABYLON = {}));
  22645. var BABYLON;
  22646. (function (BABYLON) {
  22647. var Skeleton = (function () {
  22648. function Skeleton(name, id, scene) {
  22649. this.name = name;
  22650. this.id = id;
  22651. this.bones = new Array();
  22652. this._isDirty = true;
  22653. this._identity = BABYLON.Matrix.Identity();
  22654. this.bones = [];
  22655. this._scene = scene;
  22656. scene.skeletons.push(this);
  22657. this.prepare();
  22658. //make sure it will recalculate the matrix next time prepare is called.
  22659. this._isDirty = true;
  22660. }
  22661. // Members
  22662. Skeleton.prototype.getTransformMatrices = function () {
  22663. return this._transformMatrices;
  22664. };
  22665. Skeleton.prototype.getScene = function () {
  22666. return this._scene;
  22667. };
  22668. // Methods
  22669. Skeleton.prototype._markAsDirty = function () {
  22670. this._isDirty = true;
  22671. };
  22672. Skeleton.prototype.prepare = function () {
  22673. if (!this._isDirty) {
  22674. return;
  22675. }
  22676. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22677. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22678. }
  22679. for (var index = 0; index < this.bones.length; index++) {
  22680. var bone = this.bones[index];
  22681. var parentBone = bone.getParent();
  22682. if (parentBone) {
  22683. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22684. }
  22685. else {
  22686. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22687. }
  22688. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22689. }
  22690. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22691. this._isDirty = false;
  22692. this._scene._activeBones += this.bones.length;
  22693. };
  22694. Skeleton.prototype.getAnimatables = function () {
  22695. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22696. this._animatables = [];
  22697. for (var index = 0; index < this.bones.length; index++) {
  22698. this._animatables.push(this.bones[index]);
  22699. }
  22700. }
  22701. return this._animatables;
  22702. };
  22703. Skeleton.prototype.clone = function (name, id) {
  22704. var result = new Skeleton(name, id || name, this._scene);
  22705. for (var index = 0; index < this.bones.length; index++) {
  22706. var source = this.bones[index];
  22707. var parentBone = null;
  22708. if (source.getParent()) {
  22709. var parentIndex = this.bones.indexOf(source.getParent());
  22710. parentBone = result.bones[parentIndex];
  22711. }
  22712. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22713. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22714. }
  22715. return result;
  22716. };
  22717. return Skeleton;
  22718. })();
  22719. BABYLON.Skeleton = Skeleton;
  22720. })(BABYLON || (BABYLON = {}));
  22721. var BABYLON;
  22722. (function (BABYLON) {
  22723. var PostProcess = (function () {
  22724. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22727. this.name = name;
  22728. this.width = -1;
  22729. this.height = -1;
  22730. this._reusable = false;
  22731. this._textures = new BABYLON.SmartArray(2);
  22732. this._currentRenderTextureInd = 0;
  22733. if (camera != null) {
  22734. this._camera = camera;
  22735. this._scene = camera.getScene();
  22736. camera.attachPostProcess(this);
  22737. this._engine = this._scene.getEngine();
  22738. }
  22739. else {
  22740. this._engine = engine;
  22741. }
  22742. this._renderRatio = ratio;
  22743. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22744. this._reusable = reusable || false;
  22745. this._textureType = textureType;
  22746. samplers = samplers || [];
  22747. samplers.push("textureSampler");
  22748. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22749. }
  22750. PostProcess.prototype.isReusable = function () {
  22751. return this._reusable;
  22752. };
  22753. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22754. camera = camera || this._camera;
  22755. var scene = camera.getScene();
  22756. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22757. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22758. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22759. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22760. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22761. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22762. if (this._textures.length > 0) {
  22763. for (var i = 0; i < this._textures.length; i++) {
  22764. this._engine._releaseTexture(this._textures.data[i]);
  22765. }
  22766. this._textures.reset();
  22767. }
  22768. this.width = desiredWidth;
  22769. this.height = desiredHeight;
  22770. 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, type: this._textureType }));
  22771. if (this._reusable) {
  22772. 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, type: this._textureType }));
  22773. }
  22774. if (this.onSizeChanged) {
  22775. this.onSizeChanged();
  22776. }
  22777. }
  22778. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22779. if (this.onActivate) {
  22780. this.onActivate(camera);
  22781. }
  22782. // Clear
  22783. if (this.clearColor) {
  22784. this._engine.clear(this.clearColor, true, true);
  22785. }
  22786. else {
  22787. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22788. }
  22789. if (this._reusable) {
  22790. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22791. }
  22792. };
  22793. PostProcess.prototype.apply = function () {
  22794. // Check
  22795. if (!this._effect.isReady())
  22796. return null;
  22797. // States
  22798. this._engine.enableEffect(this._effect);
  22799. this._engine.setState(false);
  22800. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22801. this._engine.setDepthBuffer(false);
  22802. this._engine.setDepthWrite(false);
  22803. // Texture
  22804. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22805. // Parameters
  22806. if (this.onApply) {
  22807. this.onApply(this._effect);
  22808. }
  22809. return this._effect;
  22810. };
  22811. PostProcess.prototype.dispose = function (camera) {
  22812. camera = camera || this._camera;
  22813. if (this._textures.length > 0) {
  22814. for (var i = 0; i < this._textures.length; i++) {
  22815. this._engine._releaseTexture(this._textures.data[i]);
  22816. }
  22817. this._textures.reset();
  22818. }
  22819. if (!camera) {
  22820. return;
  22821. }
  22822. camera.detachPostProcess(this);
  22823. var index = camera._postProcesses.indexOf(this);
  22824. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22825. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22826. }
  22827. };
  22828. return PostProcess;
  22829. })();
  22830. BABYLON.PostProcess = PostProcess;
  22831. })(BABYLON || (BABYLON = {}));
  22832. var BABYLON;
  22833. (function (BABYLON) {
  22834. var PostProcessManager = (function () {
  22835. function PostProcessManager(scene) {
  22836. this._vertexDeclaration = [2];
  22837. this._vertexStrideSize = 2 * 4;
  22838. this._scene = scene;
  22839. }
  22840. PostProcessManager.prototype._prepareBuffers = function () {
  22841. if (this._vertexBuffer) {
  22842. return;
  22843. }
  22844. // VBO
  22845. var vertices = [];
  22846. vertices.push(1, 1);
  22847. vertices.push(-1, 1);
  22848. vertices.push(-1, -1);
  22849. vertices.push(1, -1);
  22850. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22851. // Indices
  22852. var indices = [];
  22853. indices.push(0);
  22854. indices.push(1);
  22855. indices.push(2);
  22856. indices.push(0);
  22857. indices.push(2);
  22858. indices.push(3);
  22859. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22860. };
  22861. // Methods
  22862. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22863. var postProcesses = this._scene.activeCamera._postProcesses;
  22864. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22865. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22866. return false;
  22867. }
  22868. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22869. return true;
  22870. };
  22871. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22872. var engine = this._scene.getEngine();
  22873. for (var index = 0; index < postProcesses.length; index++) {
  22874. if (index < postProcesses.length - 1) {
  22875. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22876. }
  22877. else {
  22878. if (targetTexture) {
  22879. engine.bindFramebuffer(targetTexture);
  22880. }
  22881. else {
  22882. engine.restoreDefaultFramebuffer();
  22883. }
  22884. }
  22885. var pp = postProcesses[index];
  22886. var effect = pp.apply();
  22887. if (effect) {
  22888. if (pp.onBeforeRender) {
  22889. pp.onBeforeRender(effect);
  22890. }
  22891. // VBOs
  22892. this._prepareBuffers();
  22893. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22894. // Draw order
  22895. engine.draw(true, 0, 6);
  22896. if (pp.onAfterRender) {
  22897. pp.onAfterRender(effect);
  22898. }
  22899. }
  22900. }
  22901. // Restore depth buffer
  22902. engine.setDepthBuffer(true);
  22903. engine.setDepthWrite(true);
  22904. };
  22905. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22906. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22907. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22908. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22909. return;
  22910. }
  22911. var engine = this._scene.getEngine();
  22912. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22913. if (index < postProcessesTakenIndices.length - 1) {
  22914. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22915. }
  22916. else {
  22917. if (targetTexture) {
  22918. engine.bindFramebuffer(targetTexture);
  22919. }
  22920. else {
  22921. engine.restoreDefaultFramebuffer();
  22922. }
  22923. }
  22924. if (doNotPresent) {
  22925. break;
  22926. }
  22927. var pp = postProcesses[postProcessesTakenIndices[index]];
  22928. var effect = pp.apply();
  22929. if (effect) {
  22930. if (pp.onBeforeRender) {
  22931. pp.onBeforeRender(effect);
  22932. }
  22933. // VBOs
  22934. this._prepareBuffers();
  22935. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22936. // Draw order
  22937. engine.draw(true, 0, 6);
  22938. if (pp.onAfterRender) {
  22939. pp.onAfterRender(effect);
  22940. }
  22941. }
  22942. }
  22943. // Restore depth buffer
  22944. engine.setDepthBuffer(true);
  22945. engine.setDepthWrite(true);
  22946. };
  22947. PostProcessManager.prototype.dispose = function () {
  22948. if (this._vertexBuffer) {
  22949. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22950. this._vertexBuffer = null;
  22951. }
  22952. if (this._indexBuffer) {
  22953. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22954. this._indexBuffer = null;
  22955. }
  22956. };
  22957. return PostProcessManager;
  22958. })();
  22959. BABYLON.PostProcessManager = PostProcessManager;
  22960. })(BABYLON || (BABYLON = {}));
  22961. var BABYLON;
  22962. (function (BABYLON) {
  22963. var PassPostProcess = (function (_super) {
  22964. __extends(PassPostProcess, _super);
  22965. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22966. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22967. }
  22968. return PassPostProcess;
  22969. })(BABYLON.PostProcess);
  22970. BABYLON.PassPostProcess = PassPostProcess;
  22971. })(BABYLON || (BABYLON = {}));
  22972. var BABYLON;
  22973. (function (BABYLON) {
  22974. var BlurPostProcess = (function (_super) {
  22975. __extends(BlurPostProcess, _super);
  22976. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22977. var _this = this;
  22978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22979. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22980. this.direction = direction;
  22981. this.blurWidth = blurWidth;
  22982. this.onApply = function (effect) {
  22983. effect.setFloat2("screenSize", _this.width, _this.height);
  22984. effect.setVector2("direction", _this.direction);
  22985. effect.setFloat("blurWidth", _this.blurWidth);
  22986. };
  22987. }
  22988. return BlurPostProcess;
  22989. })(BABYLON.PostProcess);
  22990. BABYLON.BlurPostProcess = BlurPostProcess;
  22991. })(BABYLON || (BABYLON = {}));
  22992. var BABYLON;
  22993. (function (BABYLON) {
  22994. var RefractionPostProcess = (function (_super) {
  22995. __extends(RefractionPostProcess, _super);
  22996. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22997. var _this = this;
  22998. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22999. this.color = color;
  23000. this.depth = depth;
  23001. this.colorLevel = colorLevel;
  23002. this.onActivate = function (cam) {
  23003. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23004. };
  23005. this.onApply = function (effect) {
  23006. effect.setColor3("baseColor", _this.color);
  23007. effect.setFloat("depth", _this.depth);
  23008. effect.setFloat("colorLevel", _this.colorLevel);
  23009. effect.setTexture("refractionSampler", _this._refRexture);
  23010. };
  23011. }
  23012. // Methods
  23013. RefractionPostProcess.prototype.dispose = function (camera) {
  23014. if (this._refRexture) {
  23015. this._refRexture.dispose();
  23016. }
  23017. _super.prototype.dispose.call(this, camera);
  23018. };
  23019. return RefractionPostProcess;
  23020. })(BABYLON.PostProcess);
  23021. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23022. })(BABYLON || (BABYLON = {}));
  23023. var BABYLON;
  23024. (function (BABYLON) {
  23025. var BlackAndWhitePostProcess = (function (_super) {
  23026. __extends(BlackAndWhitePostProcess, _super);
  23027. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23028. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23029. }
  23030. return BlackAndWhitePostProcess;
  23031. })(BABYLON.PostProcess);
  23032. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23033. })(BABYLON || (BABYLON = {}));
  23034. var BABYLON;
  23035. (function (BABYLON) {
  23036. var ConvolutionPostProcess = (function (_super) {
  23037. __extends(ConvolutionPostProcess, _super);
  23038. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23039. var _this = this;
  23040. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23041. this.kernel = kernel;
  23042. this.onApply = function (effect) {
  23043. effect.setFloat2("screenSize", _this.width, _this.height);
  23044. effect.setArray("kernel", _this.kernel);
  23045. };
  23046. }
  23047. // Statics
  23048. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23049. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23050. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23051. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23052. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23053. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23054. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23055. return ConvolutionPostProcess;
  23056. })(BABYLON.PostProcess);
  23057. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23058. })(BABYLON || (BABYLON = {}));
  23059. var BABYLON;
  23060. (function (BABYLON) {
  23061. var FilterPostProcess = (function (_super) {
  23062. __extends(FilterPostProcess, _super);
  23063. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23064. var _this = this;
  23065. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23066. this.kernelMatrix = kernelMatrix;
  23067. this.onApply = function (effect) {
  23068. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23069. };
  23070. }
  23071. return FilterPostProcess;
  23072. })(BABYLON.PostProcess);
  23073. BABYLON.FilterPostProcess = FilterPostProcess;
  23074. })(BABYLON || (BABYLON = {}));
  23075. var BABYLON;
  23076. (function (BABYLON) {
  23077. var FxaaPostProcess = (function (_super) {
  23078. __extends(FxaaPostProcess, _super);
  23079. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23080. var _this = this;
  23081. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23082. this.onSizeChanged = function () {
  23083. _this.texelWidth = 1.0 / _this.width;
  23084. _this.texelHeight = 1.0 / _this.height;
  23085. };
  23086. this.onApply = function (effect) {
  23087. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23088. };
  23089. }
  23090. return FxaaPostProcess;
  23091. })(BABYLON.PostProcess);
  23092. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23093. })(BABYLON || (BABYLON = {}));
  23094. var BABYLON;
  23095. (function (BABYLON) {
  23096. var StereoscopicInterlacePostProcess = (function (_super) {
  23097. __extends(StereoscopicInterlacePostProcess, _super);
  23098. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23099. var _this = this;
  23100. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23101. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23102. this.onSizeChanged = function () {
  23103. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23104. };
  23105. this.onApply = function (effect) {
  23106. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23107. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23108. };
  23109. }
  23110. return StereoscopicInterlacePostProcess;
  23111. })(BABYLON.PostProcess);
  23112. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23113. })(BABYLON || (BABYLON = {}));
  23114. var BABYLON;
  23115. (function (BABYLON) {
  23116. var LensFlare = (function () {
  23117. function LensFlare(size, position, color, imgUrl, system) {
  23118. this.size = size;
  23119. this.position = position;
  23120. this.dispose = function () {
  23121. if (this.texture) {
  23122. this.texture.dispose();
  23123. }
  23124. // Remove from scene
  23125. var index = this._system.lensFlares.indexOf(this);
  23126. this._system.lensFlares.splice(index, 1);
  23127. };
  23128. this.color = color || new BABYLON.Color3(1, 1, 1);
  23129. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23130. this._system = system;
  23131. system.lensFlares.push(this);
  23132. }
  23133. return LensFlare;
  23134. })();
  23135. BABYLON.LensFlare = LensFlare;
  23136. })(BABYLON || (BABYLON = {}));
  23137. var BABYLON;
  23138. (function (BABYLON) {
  23139. var LensFlareSystem = (function () {
  23140. function LensFlareSystem(name, emitter, scene) {
  23141. this.name = name;
  23142. this.lensFlares = new Array();
  23143. this.borderLimit = 300;
  23144. this._vertexDeclaration = [2];
  23145. this._vertexStrideSize = 2 * 4;
  23146. this._isEnabled = true;
  23147. this._scene = scene;
  23148. this._emitter = emitter;
  23149. scene.lensFlareSystems.push(this);
  23150. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23151. // VBO
  23152. var vertices = [];
  23153. vertices.push(1, 1);
  23154. vertices.push(-1, 1);
  23155. vertices.push(-1, -1);
  23156. vertices.push(1, -1);
  23157. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23158. // Indices
  23159. var indices = [];
  23160. indices.push(0);
  23161. indices.push(1);
  23162. indices.push(2);
  23163. indices.push(0);
  23164. indices.push(2);
  23165. indices.push(3);
  23166. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23167. // Effects
  23168. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23169. }
  23170. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23171. get: function () {
  23172. return this._isEnabled;
  23173. },
  23174. set: function (value) {
  23175. this._isEnabled = value;
  23176. },
  23177. enumerable: true,
  23178. configurable: true
  23179. });
  23180. LensFlareSystem.prototype.getScene = function () {
  23181. return this._scene;
  23182. };
  23183. LensFlareSystem.prototype.getEmitter = function () {
  23184. return this._emitter;
  23185. };
  23186. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23187. this._emitter = newEmitter;
  23188. };
  23189. LensFlareSystem.prototype.getEmitterPosition = function () {
  23190. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23191. };
  23192. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23193. var position = this.getEmitterPosition();
  23194. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23195. this._positionX = position.x;
  23196. this._positionY = position.y;
  23197. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23198. if (position.z > 0) {
  23199. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23200. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23201. return true;
  23202. }
  23203. }
  23204. return false;
  23205. };
  23206. LensFlareSystem.prototype._isVisible = function () {
  23207. if (!this._isEnabled) {
  23208. return false;
  23209. }
  23210. var emitterPosition = this.getEmitterPosition();
  23211. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23212. var distance = direction.length();
  23213. direction.normalize();
  23214. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23215. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23216. return !pickInfo.hit || pickInfo.distance > distance;
  23217. };
  23218. LensFlareSystem.prototype.render = function () {
  23219. if (!this._effect.isReady())
  23220. return false;
  23221. var engine = this._scene.getEngine();
  23222. var viewport = this._scene.activeCamera.viewport;
  23223. var globalViewport = viewport.toGlobal(engine);
  23224. // Position
  23225. if (!this.computeEffectivePosition(globalViewport)) {
  23226. return false;
  23227. }
  23228. // Visibility
  23229. if (!this._isVisible()) {
  23230. return false;
  23231. }
  23232. // Intensity
  23233. var awayX;
  23234. var awayY;
  23235. if (this._positionX < this.borderLimit + globalViewport.x) {
  23236. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23237. }
  23238. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23239. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23240. }
  23241. else {
  23242. awayX = 0;
  23243. }
  23244. if (this._positionY < this.borderLimit + globalViewport.y) {
  23245. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23246. }
  23247. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23248. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23249. }
  23250. else {
  23251. awayY = 0;
  23252. }
  23253. var away = (awayX > awayY) ? awayX : awayY;
  23254. if (away > this.borderLimit) {
  23255. away = this.borderLimit;
  23256. }
  23257. var intensity = 1.0 - (away / this.borderLimit);
  23258. if (intensity < 0) {
  23259. return false;
  23260. }
  23261. if (intensity > 1.0) {
  23262. intensity = 1.0;
  23263. }
  23264. // Position
  23265. var centerX = globalViewport.x + globalViewport.width / 2;
  23266. var centerY = globalViewport.y + globalViewport.height / 2;
  23267. var distX = centerX - this._positionX;
  23268. var distY = centerY - this._positionY;
  23269. // Effects
  23270. engine.enableEffect(this._effect);
  23271. engine.setState(false);
  23272. engine.setDepthBuffer(false);
  23273. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23274. // VBOs
  23275. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23276. // Flares
  23277. for (var index = 0; index < this.lensFlares.length; index++) {
  23278. var flare = this.lensFlares[index];
  23279. var x = centerX - (distX * flare.position);
  23280. var y = centerY - (distY * flare.position);
  23281. var cw = flare.size;
  23282. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23283. var cx = 2 * (x / globalViewport.width) - 1.0;
  23284. var cy = 1.0 - 2 * (y / globalViewport.height);
  23285. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23286. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23287. // Texture
  23288. this._effect.setTexture("textureSampler", flare.texture);
  23289. // Color
  23290. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23291. // Draw order
  23292. engine.draw(true, 0, 6);
  23293. }
  23294. engine.setDepthBuffer(true);
  23295. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23296. return true;
  23297. };
  23298. LensFlareSystem.prototype.dispose = function () {
  23299. if (this._vertexBuffer) {
  23300. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23301. this._vertexBuffer = null;
  23302. }
  23303. if (this._indexBuffer) {
  23304. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23305. this._indexBuffer = null;
  23306. }
  23307. while (this.lensFlares.length) {
  23308. this.lensFlares[0].dispose();
  23309. }
  23310. // Remove from scene
  23311. var index = this._scene.lensFlareSystems.indexOf(this);
  23312. this._scene.lensFlareSystems.splice(index, 1);
  23313. };
  23314. return LensFlareSystem;
  23315. })();
  23316. BABYLON.LensFlareSystem = LensFlareSystem;
  23317. })(BABYLON || (BABYLON = {}));
  23318. var BABYLON;
  23319. (function (BABYLON) {
  23320. var CannonJSPlugin = (function () {
  23321. function CannonJSPlugin() {
  23322. this._registeredMeshes = [];
  23323. this._physicsMaterials = [];
  23324. this.updateBodyPosition = function (mesh) {
  23325. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23326. var registeredMesh = this._registeredMeshes[index];
  23327. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23328. var body = registeredMesh.body;
  23329. var center = mesh.getBoundingInfo().boundingBox.center;
  23330. body.position.set(center.x, center.z, center.y);
  23331. body.quaternion.x = mesh.rotationQuaternion.x;
  23332. body.quaternion.z = mesh.rotationQuaternion.y;
  23333. body.quaternion.y = mesh.rotationQuaternion.z;
  23334. body.quaternion.w = -mesh.rotationQuaternion.w;
  23335. return;
  23336. }
  23337. }
  23338. };
  23339. }
  23340. CannonJSPlugin.prototype.initialize = function (iterations) {
  23341. if (iterations === void 0) { iterations = 10; }
  23342. this._world = new CANNON.World();
  23343. this._world.broadphase = new CANNON.NaiveBroadphase();
  23344. this._world.solver.iterations = iterations;
  23345. };
  23346. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23347. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23348. };
  23349. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23350. this._world.step(delta);
  23351. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23352. var registeredMesh = this._registeredMeshes[index];
  23353. if (registeredMesh.isChild) {
  23354. continue;
  23355. }
  23356. // Body position
  23357. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23358. var deltaPos = registeredMesh.delta;
  23359. if (deltaPos) {
  23360. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23361. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23362. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23363. }
  23364. else {
  23365. registeredMesh.mesh.position.x = bodyX;
  23366. registeredMesh.mesh.position.y = bodyZ;
  23367. registeredMesh.mesh.position.z = bodyY;
  23368. }
  23369. if (!registeredMesh.mesh.rotationQuaternion) {
  23370. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23371. }
  23372. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23373. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23374. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23375. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23376. }
  23377. };
  23378. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23379. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23380. };
  23381. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23382. this.unregisterMesh(mesh);
  23383. mesh.computeWorldMatrix(true);
  23384. switch (impostor) {
  23385. case BABYLON.PhysicsEngine.SphereImpostor:
  23386. var bbox = mesh.getBoundingInfo().boundingBox;
  23387. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23388. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23389. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23390. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23391. case BABYLON.PhysicsEngine.BoxImpostor:
  23392. bbox = mesh.getBoundingInfo().boundingBox;
  23393. var min = bbox.minimumWorld;
  23394. var max = bbox.maximumWorld;
  23395. var box = max.subtract(min).scale(0.5);
  23396. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23397. case BABYLON.PhysicsEngine.PlaneImpostor:
  23398. return this._createPlane(mesh, options);
  23399. case BABYLON.PhysicsEngine.MeshImpostor:
  23400. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23401. var rawFaces = mesh.getIndices();
  23402. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23403. }
  23404. return null;
  23405. };
  23406. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23407. var shape = new CANNON.Sphere(radius);
  23408. if (!options) {
  23409. return shape;
  23410. }
  23411. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23412. };
  23413. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23414. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23415. if (!options) {
  23416. return shape;
  23417. }
  23418. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23419. };
  23420. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23421. var shape = new CANNON.Plane();
  23422. if (!options) {
  23423. return shape;
  23424. }
  23425. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23426. };
  23427. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23428. var verts = [], faces = [];
  23429. mesh.computeWorldMatrix(true);
  23430. // Get vertices
  23431. for (var i = 0; i < rawVerts.length; i += 3) {
  23432. var transformed = BABYLON.Vector3.Zero();
  23433. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23434. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23435. }
  23436. // Get faces
  23437. for (var j = 0; j < rawFaces.length; j += 3) {
  23438. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23439. }
  23440. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23441. if (!options) {
  23442. return shape;
  23443. }
  23444. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23445. };
  23446. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23447. var index;
  23448. var mat;
  23449. for (index = 0; index < this._physicsMaterials.length; index++) {
  23450. mat = this._physicsMaterials[index];
  23451. if (mat.friction === friction && mat.restitution === restitution) {
  23452. return mat;
  23453. }
  23454. }
  23455. var currentMat = new CANNON.Material();
  23456. currentMat.friction = friction;
  23457. currentMat.restitution = restitution;
  23458. this._physicsMaterials.push(currentMat);
  23459. for (index = 0; index < this._physicsMaterials.length; index++) {
  23460. mat = this._physicsMaterials[index];
  23461. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23462. contactMaterial.contactEquationStiffness = 1e10;
  23463. contactMaterial.contactEquationRegularizationTime = 10;
  23464. this._world.addContactMaterial(contactMaterial);
  23465. }
  23466. return currentMat;
  23467. };
  23468. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23469. var initialRotation = null;
  23470. if (mesh.rotationQuaternion) {
  23471. initialRotation = mesh.rotationQuaternion.clone();
  23472. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23473. }
  23474. // The delta between the mesh position and the mesh bounding box center
  23475. var bbox = mesh.getBoundingInfo().boundingBox;
  23476. var deltaPosition = mesh.position.subtract(bbox.center);
  23477. var material = this._addMaterial(friction, restitution);
  23478. var body = new CANNON.RigidBody(mass, shape, material);
  23479. if (initialRotation) {
  23480. body.quaternion.x = initialRotation.x;
  23481. body.quaternion.z = initialRotation.y;
  23482. body.quaternion.y = initialRotation.z;
  23483. body.quaternion.w = -initialRotation.w;
  23484. }
  23485. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23486. this._world.add(body);
  23487. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23488. return body;
  23489. };
  23490. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23491. var compoundShape = new CANNON.Compound();
  23492. for (var index = 0; index < parts.length; index++) {
  23493. var mesh = parts[index].mesh;
  23494. var shape = this.registerMesh(mesh, parts[index].impostor);
  23495. if (index == 0) {
  23496. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23497. }
  23498. else {
  23499. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23500. }
  23501. }
  23502. var initialMesh = parts[0].mesh;
  23503. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23504. body.parts = parts;
  23505. return body;
  23506. };
  23507. CannonJSPlugin.prototype._unbindBody = function (body) {
  23508. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23509. var registeredMesh = this._registeredMeshes[index];
  23510. if (registeredMesh.body === body) {
  23511. registeredMesh.body = null;
  23512. registeredMesh.delta = 0;
  23513. }
  23514. }
  23515. };
  23516. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23517. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23518. var registeredMesh = this._registeredMeshes[index];
  23519. if (registeredMesh.mesh === mesh) {
  23520. // Remove body
  23521. if (registeredMesh.body) {
  23522. this._world.remove(registeredMesh.body);
  23523. this._unbindBody(registeredMesh.body);
  23524. }
  23525. this._registeredMeshes.splice(index, 1);
  23526. return;
  23527. }
  23528. }
  23529. };
  23530. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23531. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23532. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23533. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23534. var registeredMesh = this._registeredMeshes[index];
  23535. if (registeredMesh.mesh === mesh) {
  23536. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23537. return;
  23538. }
  23539. }
  23540. };
  23541. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23542. var body1 = null, body2 = null;
  23543. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23544. var registeredMesh = this._registeredMeshes[index];
  23545. if (registeredMesh.mesh === mesh1) {
  23546. body1 = registeredMesh.body;
  23547. }
  23548. else if (registeredMesh.mesh === mesh2) {
  23549. body2 = registeredMesh.body;
  23550. }
  23551. }
  23552. if (!body1 || !body2) {
  23553. return false;
  23554. }
  23555. 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));
  23556. this._world.addConstraint(constraint);
  23557. return true;
  23558. };
  23559. CannonJSPlugin.prototype.dispose = function () {
  23560. while (this._registeredMeshes.length) {
  23561. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23562. }
  23563. };
  23564. CannonJSPlugin.prototype.isSupported = function () {
  23565. return window.CANNON !== undefined;
  23566. };
  23567. return CannonJSPlugin;
  23568. })();
  23569. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23570. })(BABYLON || (BABYLON = {}));
  23571. var BABYLON;
  23572. (function (BABYLON) {
  23573. var OimoJSPlugin = (function () {
  23574. function OimoJSPlugin() {
  23575. this._registeredMeshes = [];
  23576. /**
  23577. * Update the body position according to the mesh position
  23578. * @param mesh
  23579. */
  23580. this.updateBodyPosition = function (mesh) {
  23581. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23582. var registeredMesh = this._registeredMeshes[index];
  23583. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23584. var body = registeredMesh.body.body;
  23585. mesh.computeWorldMatrix(true);
  23586. var center = mesh.getBoundingInfo().boundingBox.center;
  23587. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23588. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23589. body.sleeping = false;
  23590. return;
  23591. }
  23592. // Case where the parent has been updated
  23593. if (registeredMesh.mesh.parent === mesh) {
  23594. mesh.computeWorldMatrix(true);
  23595. registeredMesh.mesh.computeWorldMatrix(true);
  23596. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23597. var absoluteRotation = mesh.rotation;
  23598. body = registeredMesh.body.body;
  23599. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23600. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23601. body.sleeping = false;
  23602. return;
  23603. }
  23604. }
  23605. };
  23606. }
  23607. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23608. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23609. };
  23610. OimoJSPlugin.prototype.initialize = function (iterations) {
  23611. this._world = new OIMO.World();
  23612. this._world.clear();
  23613. };
  23614. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23615. this._world.gravity = gravity;
  23616. };
  23617. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23618. var body = null;
  23619. this.unregisterMesh(mesh);
  23620. mesh.computeWorldMatrix(true);
  23621. var initialRotation = null;
  23622. if (mesh.rotationQuaternion) {
  23623. initialRotation = mesh.rotationQuaternion.clone();
  23624. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23625. mesh.computeWorldMatrix(true);
  23626. }
  23627. var bbox = mesh.getBoundingInfo().boundingBox;
  23628. // The delta between the mesh position and the mesh bounding box center
  23629. var deltaPosition = mesh.position.subtract(bbox.center);
  23630. // Transform delta position with the rotation
  23631. if (initialRotation) {
  23632. var m = new BABYLON.Matrix();
  23633. initialRotation.toRotationMatrix(m);
  23634. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23635. }
  23636. // register mesh
  23637. switch (impostor) {
  23638. case BABYLON.PhysicsEngine.SphereImpostor:
  23639. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23640. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23641. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23642. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23643. body = new OIMO.Body({
  23644. type: 'sphere',
  23645. size: [size],
  23646. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23647. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23648. move: options.mass != 0,
  23649. config: [options.mass, options.friction, options.restitution],
  23650. world: this._world
  23651. });
  23652. break;
  23653. case BABYLON.PhysicsEngine.PlaneImpostor:
  23654. //Oimo "fakes" a cylinder as a box, so why don't we!
  23655. case BABYLON.PhysicsEngine.CylinderImpostor:
  23656. case BABYLON.PhysicsEngine.BoxImpostor:
  23657. var min = bbox.minimumWorld;
  23658. var max = bbox.maximumWorld;
  23659. var box = max.subtract(min);
  23660. var sizeX = this._checkWithEpsilon(box.x);
  23661. var sizeY = this._checkWithEpsilon(box.y);
  23662. var sizeZ = this._checkWithEpsilon(box.z);
  23663. body = new OIMO.Body({
  23664. type: 'box',
  23665. size: [sizeX, sizeY, sizeZ],
  23666. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23667. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23668. move: options.mass != 0,
  23669. config: [options.mass, options.friction, options.restitution],
  23670. world: this._world
  23671. });
  23672. break;
  23673. }
  23674. //If quaternion was set as the rotation of the object
  23675. if (initialRotation) {
  23676. //We have to access the rigid body's properties to set the quaternion.
  23677. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23678. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23679. //update the internal rotation matrix
  23680. body.body.syncShapes();
  23681. }
  23682. this._registeredMeshes.push({
  23683. mesh: mesh,
  23684. body: body,
  23685. delta: deltaPosition
  23686. });
  23687. return body;
  23688. };
  23689. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23690. var types = [], sizes = [], positions = [], rotations = [];
  23691. var initialMesh = parts[0].mesh;
  23692. for (var index = 0; index < parts.length; index++) {
  23693. var part = parts[index];
  23694. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23695. types.push(bodyParameters.type);
  23696. sizes.push.apply(sizes, bodyParameters.size);
  23697. positions.push.apply(positions, bodyParameters.pos);
  23698. rotations.push.apply(rotations, bodyParameters.rot);
  23699. }
  23700. var body = new OIMO.Body({
  23701. type: types,
  23702. size: sizes,
  23703. pos: positions,
  23704. rot: rotations,
  23705. move: options.mass != 0,
  23706. config: [options.mass, options.friction, options.restitution],
  23707. world: this._world
  23708. });
  23709. this._registeredMeshes.push({
  23710. mesh: initialMesh,
  23711. body: body
  23712. });
  23713. return body;
  23714. };
  23715. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23716. var bodyParameters = null;
  23717. var mesh = part.mesh;
  23718. // We need the bounding box/sphere info to compute the physics body
  23719. mesh.computeWorldMatrix();
  23720. switch (part.impostor) {
  23721. case BABYLON.PhysicsEngine.SphereImpostor:
  23722. var bbox = mesh.getBoundingInfo().boundingBox;
  23723. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23724. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23725. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23726. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23727. bodyParameters = {
  23728. type: 'sphere',
  23729. /* bug with oimo : sphere needs 3 sizes in this case */
  23730. size: [size, -1, -1],
  23731. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23732. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23733. };
  23734. break;
  23735. case BABYLON.PhysicsEngine.PlaneImpostor:
  23736. case BABYLON.PhysicsEngine.BoxImpostor:
  23737. bbox = mesh.getBoundingInfo().boundingBox;
  23738. var min = bbox.minimumWorld;
  23739. var max = bbox.maximumWorld;
  23740. var box = max.subtract(min);
  23741. var sizeX = this._checkWithEpsilon(box.x);
  23742. var sizeY = this._checkWithEpsilon(box.y);
  23743. var sizeZ = this._checkWithEpsilon(box.z);
  23744. var relativePosition = mesh.position;
  23745. bodyParameters = {
  23746. type: 'box',
  23747. size: [sizeX, sizeY, sizeZ],
  23748. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23749. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23750. };
  23751. break;
  23752. }
  23753. return bodyParameters;
  23754. };
  23755. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23756. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23757. var registeredMesh = this._registeredMeshes[index];
  23758. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23759. if (registeredMesh.body) {
  23760. this._world.removeRigidBody(registeredMesh.body.body);
  23761. this._unbindBody(registeredMesh.body);
  23762. }
  23763. this._registeredMeshes.splice(index, 1);
  23764. return;
  23765. }
  23766. }
  23767. };
  23768. OimoJSPlugin.prototype._unbindBody = function (body) {
  23769. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23770. var registeredMesh = this._registeredMeshes[index];
  23771. if (registeredMesh.body === body) {
  23772. registeredMesh.body = null;
  23773. }
  23774. }
  23775. };
  23776. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23777. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23778. var registeredMesh = this._registeredMeshes[index];
  23779. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23780. // Get object mass to have a behaviour similar to cannon.js
  23781. var mass = registeredMesh.body.body.massInfo.mass;
  23782. // The force is scaled with the mass of object
  23783. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23784. return;
  23785. }
  23786. }
  23787. };
  23788. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23789. var body1 = null, body2 = null;
  23790. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23791. var registeredMesh = this._registeredMeshes[index];
  23792. if (registeredMesh.mesh === mesh1) {
  23793. body1 = registeredMesh.body.body;
  23794. }
  23795. else if (registeredMesh.mesh === mesh2) {
  23796. body2 = registeredMesh.body.body;
  23797. }
  23798. }
  23799. if (!body1 || !body2) {
  23800. return false;
  23801. }
  23802. if (!options) {
  23803. options = {};
  23804. }
  23805. new OIMO.Link({
  23806. type: options.type,
  23807. body1: body1,
  23808. body2: body2,
  23809. min: options.min,
  23810. max: options.max,
  23811. axe1: options.axe1,
  23812. axe2: options.axe2,
  23813. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23814. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23815. collision: options.collision,
  23816. spring: options.spring,
  23817. world: this._world
  23818. });
  23819. return true;
  23820. };
  23821. OimoJSPlugin.prototype.dispose = function () {
  23822. this._world.clear();
  23823. while (this._registeredMeshes.length) {
  23824. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23825. }
  23826. };
  23827. OimoJSPlugin.prototype.isSupported = function () {
  23828. return OIMO !== undefined;
  23829. };
  23830. OimoJSPlugin.prototype._getLastShape = function (body) {
  23831. var lastShape = body.shapes;
  23832. while (lastShape.next) {
  23833. lastShape = lastShape.next;
  23834. }
  23835. return lastShape;
  23836. };
  23837. OimoJSPlugin.prototype.runOneStep = function (time) {
  23838. this._world.step();
  23839. // Update the position of all registered meshes
  23840. var i = this._registeredMeshes.length;
  23841. var m;
  23842. while (i--) {
  23843. var body = this._registeredMeshes[i].body.body;
  23844. var mesh = this._registeredMeshes[i].mesh;
  23845. var delta = this._registeredMeshes[i].delta;
  23846. if (!body.sleeping) {
  23847. if (body.shapes.next) {
  23848. var parentShape = this._getLastShape(body);
  23849. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23850. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23851. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23852. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23853. if (!mesh.rotationQuaternion) {
  23854. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23855. }
  23856. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23857. mesh.computeWorldMatrix();
  23858. }
  23859. else {
  23860. m = body.getMatrix();
  23861. mtx = BABYLON.Matrix.FromArray(m);
  23862. // Body position
  23863. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23864. if (!delta) {
  23865. mesh.position.x = bodyX;
  23866. mesh.position.y = bodyY;
  23867. mesh.position.z = bodyZ;
  23868. }
  23869. else {
  23870. mesh.position.x = bodyX + delta.x;
  23871. mesh.position.y = bodyY + delta.y;
  23872. mesh.position.z = bodyZ + delta.z;
  23873. }
  23874. if (!mesh.rotationQuaternion) {
  23875. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23876. }
  23877. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23878. mesh.computeWorldMatrix();
  23879. }
  23880. }
  23881. }
  23882. };
  23883. return OimoJSPlugin;
  23884. })();
  23885. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23886. })(BABYLON || (BABYLON = {}));
  23887. var BABYLON;
  23888. (function (BABYLON) {
  23889. var PhysicsEngine = (function () {
  23890. function PhysicsEngine(plugin) {
  23891. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23892. }
  23893. PhysicsEngine.prototype._initialize = function (gravity) {
  23894. this._currentPlugin.initialize();
  23895. this._setGravity(gravity);
  23896. };
  23897. PhysicsEngine.prototype._runOneStep = function (delta) {
  23898. if (delta > 0.1) {
  23899. delta = 0.1;
  23900. }
  23901. else if (delta <= 0) {
  23902. delta = 1.0 / 60.0;
  23903. }
  23904. this._currentPlugin.runOneStep(delta);
  23905. };
  23906. PhysicsEngine.prototype._setGravity = function (gravity) {
  23907. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23908. this._currentPlugin.setGravity(this.gravity);
  23909. };
  23910. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23911. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23912. };
  23913. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23914. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23915. };
  23916. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23917. this._currentPlugin.unregisterMesh(mesh);
  23918. };
  23919. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23920. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23921. };
  23922. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23923. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23924. };
  23925. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23926. this._currentPlugin.updateBodyPosition(mesh);
  23927. };
  23928. PhysicsEngine.prototype.dispose = function () {
  23929. this._currentPlugin.dispose();
  23930. };
  23931. PhysicsEngine.prototype.isSupported = function () {
  23932. return this._currentPlugin.isSupported();
  23933. };
  23934. // Statics
  23935. PhysicsEngine.NoImpostor = 0;
  23936. PhysicsEngine.SphereImpostor = 1;
  23937. PhysicsEngine.BoxImpostor = 2;
  23938. PhysicsEngine.PlaneImpostor = 3;
  23939. PhysicsEngine.MeshImpostor = 4;
  23940. PhysicsEngine.CapsuleImpostor = 5;
  23941. PhysicsEngine.ConeImpostor = 6;
  23942. PhysicsEngine.CylinderImpostor = 7;
  23943. PhysicsEngine.ConvexHullImpostor = 8;
  23944. PhysicsEngine.Epsilon = 0.001;
  23945. return PhysicsEngine;
  23946. })();
  23947. BABYLON.PhysicsEngine = PhysicsEngine;
  23948. })(BABYLON || (BABYLON = {}));
  23949. var BABYLON;
  23950. (function (BABYLON) {
  23951. var serializeLight = function (light) {
  23952. var serializationObject = {};
  23953. serializationObject.name = light.name;
  23954. serializationObject.id = light.id;
  23955. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23956. if (light instanceof BABYLON.PointLight) {
  23957. serializationObject.type = 0;
  23958. serializationObject.position = (light).position.asArray();
  23959. }
  23960. else if (light instanceof BABYLON.DirectionalLight) {
  23961. serializationObject.type = 1;
  23962. var directionalLight = light;
  23963. serializationObject.position = directionalLight.position.asArray();
  23964. serializationObject.direction = directionalLight.direction.asArray();
  23965. }
  23966. else if (light instanceof BABYLON.SpotLight) {
  23967. serializationObject.type = 2;
  23968. var spotLight = light;
  23969. serializationObject.position = spotLight.position.asArray();
  23970. serializationObject.direction = spotLight.position.asArray();
  23971. serializationObject.angle = spotLight.angle;
  23972. serializationObject.exponent = spotLight.exponent;
  23973. }
  23974. else if (light instanceof BABYLON.HemisphericLight) {
  23975. serializationObject.type = 3;
  23976. var hemisphericLight = light;
  23977. serializationObject.direction = hemisphericLight.direction.asArray();
  23978. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23979. }
  23980. if (light.intensity) {
  23981. serializationObject.intensity = light.intensity;
  23982. }
  23983. serializationObject.range = light.range;
  23984. serializationObject.diffuse = light.diffuse.asArray();
  23985. serializationObject.specular = light.specular.asArray();
  23986. return serializationObject;
  23987. };
  23988. var serializeFresnelParameter = function (fresnelParameter) {
  23989. var serializationObject = {};
  23990. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23991. serializationObject.leftColor = fresnelParameter.leftColor;
  23992. serializationObject.rightColor = fresnelParameter.rightColor;
  23993. serializationObject.bias = fresnelParameter.bias;
  23994. serializationObject.power = fresnelParameter.power;
  23995. return serializationObject;
  23996. };
  23997. var serializeAnimation;
  23998. var appendAnimations = function (source, destination) {
  23999. if (source.animations) {
  24000. destination.animations = [];
  24001. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24002. var animation = source.animations[animationIndex];
  24003. destination.animations.push(serializeAnimation(animation));
  24004. }
  24005. }
  24006. };
  24007. var serializeCamera = function (camera) {
  24008. var serializationObject = {};
  24009. serializationObject.name = camera.name;
  24010. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24011. serializationObject.id = camera.id;
  24012. serializationObject.position = camera.position.asArray();
  24013. // Parent
  24014. if (camera.parent) {
  24015. serializationObject.parentId = camera.parent.id;
  24016. }
  24017. serializationObject.fov = camera.fov;
  24018. serializationObject.minZ = camera.minZ;
  24019. serializationObject.maxZ = camera.maxZ;
  24020. serializationObject.inertia = camera.inertia;
  24021. //setting the type
  24022. if (camera instanceof BABYLON.FreeCamera) {
  24023. serializationObject.type = "FreeCamera";
  24024. }
  24025. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24026. serializationObject.type = "ArcRotateCamera";
  24027. }
  24028. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24029. serializationObject.type = "AnaglyphArcRotateCamera";
  24030. }
  24031. else if (camera instanceof BABYLON.GamepadCamera) {
  24032. serializationObject.type = "GamepadCamera";
  24033. }
  24034. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24035. serializationObject.type = "AnaglyphFreeCamera";
  24036. }
  24037. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24038. serializationObject.type = "DeviceOrientationCamera";
  24039. }
  24040. else if (camera instanceof BABYLON.FollowCamera) {
  24041. serializationObject.type = "FollowCamera";
  24042. }
  24043. else if (camera instanceof BABYLON.TouchCamera) {
  24044. serializationObject.type = "TouchCamera";
  24045. }
  24046. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24047. serializationObject.type = "VirtualJoysticksCamera";
  24048. }
  24049. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24050. serializationObject.type = "WebVRFreeCamera";
  24051. }
  24052. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24053. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24054. }
  24055. //special properties of specific cameras
  24056. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24057. var arcCamera = camera;
  24058. serializationObject.alpha = arcCamera.alpha;
  24059. serializationObject.beta = arcCamera.beta;
  24060. serializationObject.radius = arcCamera.radius;
  24061. if (arcCamera.target && arcCamera.target.id) {
  24062. serializationObject.lockedTargetId = arcCamera.target.id;
  24063. }
  24064. }
  24065. else if (camera instanceof BABYLON.FollowCamera) {
  24066. var followCam = camera;
  24067. serializationObject.radius = followCam.radius;
  24068. serializationObject.heightOffset = followCam.heightOffset;
  24069. serializationObject.rotationOffset = followCam.rotationOffset;
  24070. }
  24071. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24072. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  24073. if (camera['_interaxialDistance'] !== undefined) {
  24074. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24075. }
  24076. }
  24077. //general properties that not all cameras have. The [] is due to typescript's type safety
  24078. if (camera['speed'] !== undefined) {
  24079. serializationObject.speed = camera['speed'];
  24080. }
  24081. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24082. serializationObject.target = camera['target'].asArray();
  24083. }
  24084. // Target
  24085. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24086. serializationObject.rotation = camera['rotation'].asArray();
  24087. }
  24088. // Locked target
  24089. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24090. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24091. }
  24092. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24093. serializationObject.applyGravity = camera['applyGravity'] || false;
  24094. if (camera['ellipsoid']) {
  24095. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24096. }
  24097. // Animations
  24098. appendAnimations(camera, serializationObject);
  24099. // Layer mask
  24100. serializationObject.layerMask = camera.layerMask;
  24101. return serializationObject;
  24102. };
  24103. serializeAnimation = function (animation) {
  24104. var serializationObject = {};
  24105. serializationObject.name = animation.name;
  24106. serializationObject.property = animation.targetProperty;
  24107. serializationObject.framePerSecond = animation.framePerSecond;
  24108. serializationObject.dataType = animation.dataType;
  24109. serializationObject.loopBehavior = animation.loopMode;
  24110. var dataType = animation.dataType;
  24111. serializationObject.keys = [];
  24112. var keys = animation.getKeys();
  24113. for (var index = 0; index < keys.length; index++) {
  24114. var animationKey = keys[index];
  24115. var key = {};
  24116. key.frame = animationKey.frame;
  24117. switch (dataType) {
  24118. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24119. key.values = [animationKey.value];
  24120. break;
  24121. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24122. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24123. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24124. key.values = animationKey.value.asArray();
  24125. break;
  24126. }
  24127. serializationObject.keys.push(key);
  24128. }
  24129. return serializationObject;
  24130. };
  24131. var serializeMultiMaterial = function (material) {
  24132. var serializationObject = {};
  24133. serializationObject.name = material.name;
  24134. serializationObject.id = material.id;
  24135. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24136. serializationObject.materials = [];
  24137. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24138. var subMat = material.subMaterials[matIndex];
  24139. if (subMat) {
  24140. serializationObject.materials.push(subMat.id);
  24141. }
  24142. else {
  24143. serializationObject.materials.push(null);
  24144. }
  24145. }
  24146. return serializationObject;
  24147. };
  24148. var serializeTexture;
  24149. var serializeMaterial = function (material) {
  24150. var serializationObject = {};
  24151. serializationObject.name = material.name;
  24152. serializationObject.ambient = material.ambientColor.asArray();
  24153. serializationObject.diffuse = material.diffuseColor.asArray();
  24154. serializationObject.specular = material.specularColor.asArray();
  24155. serializationObject.specularPower = material.specularPower;
  24156. serializationObject.emissive = material.emissiveColor.asArray();
  24157. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24158. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24159. serializationObject.alpha = material.alpha;
  24160. serializationObject.id = material.id;
  24161. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24162. serializationObject.backFaceCulling = material.backFaceCulling;
  24163. if (material.diffuseTexture) {
  24164. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24165. }
  24166. if (material.diffuseFresnelParameters) {
  24167. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24168. }
  24169. if (material.ambientTexture) {
  24170. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24171. }
  24172. if (material.opacityTexture) {
  24173. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24174. }
  24175. if (material.opacityFresnelParameters) {
  24176. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24177. }
  24178. if (material.reflectionTexture) {
  24179. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24180. }
  24181. if (material.reflectionFresnelParameters) {
  24182. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24183. }
  24184. if (material.emissiveTexture) {
  24185. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24186. }
  24187. if (material.emissiveFresnelParameters) {
  24188. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24189. }
  24190. if (material.specularTexture) {
  24191. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24192. }
  24193. if (material.bumpTexture) {
  24194. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24195. }
  24196. return serializationObject;
  24197. };
  24198. serializeTexture = function (texture) {
  24199. var serializationObject = {};
  24200. if (!texture.name) {
  24201. return null;
  24202. }
  24203. if (texture instanceof BABYLON.CubeTexture) {
  24204. serializationObject.name = texture.name;
  24205. serializationObject.hasAlpha = texture.hasAlpha;
  24206. serializationObject.isCube = true;
  24207. serializationObject.level = texture.level;
  24208. serializationObject.coordinatesMode = texture.coordinatesMode;
  24209. return serializationObject;
  24210. }
  24211. var index;
  24212. if (texture instanceof BABYLON.MirrorTexture) {
  24213. var mirrorTexture = texture;
  24214. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24215. serializationObject.renderList = [];
  24216. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24217. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24218. }
  24219. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24220. }
  24221. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24222. var renderTargetTexture = texture;
  24223. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24224. serializationObject.renderList = [];
  24225. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24226. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24227. }
  24228. }
  24229. var regularTexture = texture;
  24230. serializationObject.name = texture.name;
  24231. serializationObject.hasAlpha = texture.hasAlpha;
  24232. serializationObject.level = texture.level;
  24233. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24234. serializationObject.coordinatesMode = texture.coordinatesMode;
  24235. serializationObject.uOffset = regularTexture.uOffset;
  24236. serializationObject.vOffset = regularTexture.vOffset;
  24237. serializationObject.uScale = regularTexture.uScale;
  24238. serializationObject.vScale = regularTexture.vScale;
  24239. serializationObject.uAng = regularTexture.uAng;
  24240. serializationObject.vAng = regularTexture.vAng;
  24241. serializationObject.wAng = regularTexture.wAng;
  24242. serializationObject.wrapU = texture.wrapU;
  24243. serializationObject.wrapV = texture.wrapV;
  24244. // Animations
  24245. appendAnimations(texture, serializationObject);
  24246. return serializationObject;
  24247. };
  24248. var serializeSkeleton = function (skeleton) {
  24249. var serializationObject = {};
  24250. serializationObject.name = skeleton.name;
  24251. serializationObject.id = skeleton.id;
  24252. serializationObject.bones = [];
  24253. for (var index = 0; index < skeleton.bones.length; index++) {
  24254. var bone = skeleton.bones[index];
  24255. var serializedBone = {
  24256. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24257. name: bone.name,
  24258. matrix: bone.getLocalMatrix().toArray()
  24259. };
  24260. serializationObject.bones.push(serializedBone);
  24261. if (bone.animations && bone.animations.length > 0) {
  24262. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24263. }
  24264. }
  24265. return serializationObject;
  24266. };
  24267. var serializeParticleSystem = function (particleSystem) {
  24268. var serializationObject = {};
  24269. serializationObject.emitterId = particleSystem.emitter.id;
  24270. serializationObject.capacity = particleSystem.getCapacity();
  24271. if (particleSystem.particleTexture) {
  24272. serializationObject.textureName = particleSystem.particleTexture.name;
  24273. }
  24274. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24275. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24276. serializationObject.minSize = particleSystem.minSize;
  24277. serializationObject.maxSize = particleSystem.maxSize;
  24278. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24279. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24280. serializationObject.emitRate = particleSystem.emitRate;
  24281. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24282. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24283. serializationObject.gravity = particleSystem.gravity.asArray();
  24284. serializationObject.direction1 = particleSystem.direction1.asArray();
  24285. serializationObject.direction2 = particleSystem.direction2.asArray();
  24286. serializationObject.color1 = particleSystem.color1.asArray();
  24287. serializationObject.color2 = particleSystem.color2.asArray();
  24288. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24289. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24290. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24291. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24292. serializationObject.blendMode = particleSystem.blendMode;
  24293. return serializationObject;
  24294. };
  24295. var serializeLensFlareSystem = function (lensFlareSystem) {
  24296. var serializationObject = {};
  24297. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24298. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24299. serializationObject.flares = [];
  24300. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24301. var flare = lensFlareSystem.lensFlares[index];
  24302. serializationObject.flares.push({
  24303. size: flare.size,
  24304. position: flare.position,
  24305. color: flare.color.asArray(),
  24306. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24307. });
  24308. }
  24309. return serializationObject;
  24310. };
  24311. var serializeShadowGenerator = function (light) {
  24312. var serializationObject = {};
  24313. var shadowGenerator = light.getShadowGenerator();
  24314. serializationObject.lightId = light.id;
  24315. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24316. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24317. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24318. serializationObject.renderList = [];
  24319. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24320. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24321. serializationObject.renderList.push(mesh.id);
  24322. }
  24323. return serializationObject;
  24324. };
  24325. var serializedGeometries = [];
  24326. var serializeVertexData;
  24327. var serializeTorusKnot;
  24328. var serializePlane;
  24329. var serializeGround;
  24330. var serializeTorus;
  24331. var serializeCylinder;
  24332. var serializeSphere;
  24333. var serializeBox;
  24334. var serializeGeometry = function (geometry, serializationGeometries) {
  24335. if (serializedGeometries[geometry.id]) {
  24336. return;
  24337. }
  24338. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24339. serializationGeometries.boxes.push(serializeBox(geometry));
  24340. }
  24341. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24342. serializationGeometries.spheres.push(serializeSphere(geometry));
  24343. }
  24344. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24345. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24346. }
  24347. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24348. serializationGeometries.toruses.push(serializeTorus(geometry));
  24349. }
  24350. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24351. serializationGeometries.grounds.push(serializeGround(geometry));
  24352. }
  24353. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24354. serializationGeometries.planes.push(serializePlane(geometry));
  24355. }
  24356. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24357. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24358. }
  24359. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24360. throw new Error("Unknown primitive type");
  24361. }
  24362. else {
  24363. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24364. }
  24365. serializedGeometries[geometry.id] = true;
  24366. };
  24367. var serializeGeometryBase = function (geometry) {
  24368. var serializationObject = {};
  24369. serializationObject.id = geometry.id;
  24370. if (BABYLON.Tags.HasTags(geometry)) {
  24371. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24372. }
  24373. return serializationObject;
  24374. };
  24375. serializeVertexData = function (vertexData) {
  24376. var serializationObject = serializeGeometryBase(vertexData);
  24377. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24378. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24379. }
  24380. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24381. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24382. }
  24383. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24384. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24385. }
  24386. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24387. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24388. }
  24389. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24390. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24391. }
  24392. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24393. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24394. }
  24395. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24396. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24397. }
  24398. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24399. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24400. }
  24401. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24402. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24403. }
  24404. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24405. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24406. serializationObject.matricesIndices._isExpanded = true;
  24407. }
  24408. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24409. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24410. }
  24411. serializationObject.indices = vertexData.getIndices();
  24412. return serializationObject;
  24413. };
  24414. var serializePrimitive = function (primitive) {
  24415. var serializationObject = serializeGeometryBase(primitive);
  24416. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24417. return serializationObject;
  24418. };
  24419. serializeBox = function (box) {
  24420. var serializationObject = serializePrimitive(box);
  24421. serializationObject.size = box.size;
  24422. return serializationObject;
  24423. };
  24424. serializeSphere = function (sphere) {
  24425. var serializationObject = serializePrimitive(sphere);
  24426. serializationObject.segments = sphere.segments;
  24427. serializationObject.diameter = sphere.diameter;
  24428. return serializationObject;
  24429. };
  24430. serializeCylinder = function (cylinder) {
  24431. var serializationObject = serializePrimitive(cylinder);
  24432. serializationObject.height = cylinder.height;
  24433. serializationObject.diameterTop = cylinder.diameterTop;
  24434. serializationObject.diameterBottom = cylinder.diameterBottom;
  24435. serializationObject.tessellation = cylinder.tessellation;
  24436. return serializationObject;
  24437. };
  24438. serializeTorus = function (torus) {
  24439. var serializationObject = serializePrimitive(torus);
  24440. serializationObject.diameter = torus.diameter;
  24441. serializationObject.thickness = torus.thickness;
  24442. serializationObject.tessellation = torus.tessellation;
  24443. return serializationObject;
  24444. };
  24445. serializeGround = function (ground) {
  24446. var serializationObject = serializePrimitive(ground);
  24447. serializationObject.width = ground.width;
  24448. serializationObject.height = ground.height;
  24449. serializationObject.subdivisions = ground.subdivisions;
  24450. return serializationObject;
  24451. };
  24452. serializePlane = function (plane) {
  24453. var serializationObject = serializePrimitive(plane);
  24454. serializationObject.size = plane.size;
  24455. return serializationObject;
  24456. };
  24457. serializeTorusKnot = function (torusKnot) {
  24458. var serializationObject = serializePrimitive(torusKnot);
  24459. serializationObject.radius = torusKnot.radius;
  24460. serializationObject.tube = torusKnot.tube;
  24461. serializationObject.radialSegments = torusKnot.radialSegments;
  24462. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24463. serializationObject.p = torusKnot.p;
  24464. serializationObject.q = torusKnot.q;
  24465. return serializationObject;
  24466. };
  24467. var serializeMesh = function (mesh, serializationScene) {
  24468. var serializationObject = {};
  24469. serializationObject.name = mesh.name;
  24470. serializationObject.id = mesh.id;
  24471. if (BABYLON.Tags.HasTags(mesh)) {
  24472. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24473. }
  24474. serializationObject.position = mesh.position.asArray();
  24475. if (mesh.rotationQuaternion) {
  24476. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24477. }
  24478. else if (mesh.rotation) {
  24479. serializationObject.rotation = mesh.rotation.asArray();
  24480. }
  24481. serializationObject.scaling = mesh.scaling.asArray();
  24482. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24483. serializationObject.isEnabled = mesh.isEnabled();
  24484. serializationObject.isVisible = mesh.isVisible;
  24485. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24486. serializationObject.pickable = mesh.isPickable;
  24487. serializationObject.receiveShadows = mesh.receiveShadows;
  24488. serializationObject.billboardMode = mesh.billboardMode;
  24489. serializationObject.visibility = mesh.visibility;
  24490. serializationObject.checkCollisions = mesh.checkCollisions;
  24491. // Parent
  24492. if (mesh.parent) {
  24493. serializationObject.parentId = mesh.parent.id;
  24494. }
  24495. // Geometry
  24496. var geometry = mesh._geometry;
  24497. if (geometry) {
  24498. var geometryId = geometry.id;
  24499. serializationObject.geometryId = geometryId;
  24500. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24501. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  24502. serializeGeometry(geometry, serializationScene.geometries);
  24503. }
  24504. // SubMeshes
  24505. serializationObject.subMeshes = [];
  24506. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24507. var subMesh = mesh.subMeshes[subIndex];
  24508. serializationObject.subMeshes.push({
  24509. materialIndex: subMesh.materialIndex,
  24510. verticesStart: subMesh.verticesStart,
  24511. verticesCount: subMesh.verticesCount,
  24512. indexStart: subMesh.indexStart,
  24513. indexCount: subMesh.indexCount
  24514. });
  24515. }
  24516. }
  24517. // Material
  24518. if (mesh.material) {
  24519. serializationObject.materialId = mesh.material.id;
  24520. }
  24521. else {
  24522. mesh.material = null;
  24523. }
  24524. // Skeleton
  24525. if (mesh.skeleton) {
  24526. serializationObject.skeletonId = mesh.skeleton.id;
  24527. }
  24528. // Physics
  24529. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24530. serializationObject.physicsMass = mesh.getPhysicsMass();
  24531. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24532. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24533. switch (mesh.getPhysicsImpostor()) {
  24534. case BABYLON.PhysicsEngine.BoxImpostor:
  24535. serializationObject.physicsImpostor = 1;
  24536. break;
  24537. case BABYLON.PhysicsEngine.SphereImpostor:
  24538. serializationObject.physicsImpostor = 2;
  24539. break;
  24540. }
  24541. }
  24542. // Instances
  24543. serializationObject.instances = [];
  24544. for (var index = 0; index < mesh.instances.length; index++) {
  24545. var instance = mesh.instances[index];
  24546. var serializationInstance = {
  24547. name: instance.name,
  24548. position: instance.position,
  24549. rotation: instance.rotation,
  24550. rotationQuaternion: instance.rotationQuaternion,
  24551. scaling: instance.scaling
  24552. };
  24553. serializationObject.instances.push(serializationInstance);
  24554. // Animations
  24555. appendAnimations(instance, serializationInstance);
  24556. }
  24557. // Animations
  24558. appendAnimations(mesh, serializationObject);
  24559. // Layer mask
  24560. serializationObject.layerMask = mesh.layerMask;
  24561. return serializationObject;
  24562. };
  24563. var finalizeSingleMesh = function (mesh, serializationObject) {
  24564. //only works if the mesh is already loaded
  24565. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24566. //serialize material
  24567. if (mesh.material) {
  24568. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24569. serializationObject.materials = serializationObject.materials || [];
  24570. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24571. serializationObject.materials.push(serializeMaterial(mesh.material));
  24572. }
  24573. }
  24574. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24575. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24576. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24577. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24578. }
  24579. }
  24580. }
  24581. //serialize geometry
  24582. var geometry = mesh._geometry;
  24583. if (geometry) {
  24584. if (!serializationObject.geometries) {
  24585. serializationObject.geometries = {};
  24586. serializationObject.geometries.boxes = [];
  24587. serializationObject.geometries.spheres = [];
  24588. serializationObject.geometries.cylinders = [];
  24589. serializationObject.geometries.toruses = [];
  24590. serializationObject.geometries.grounds = [];
  24591. serializationObject.geometries.planes = [];
  24592. serializationObject.geometries.torusKnots = [];
  24593. serializationObject.geometries.vertexData = [];
  24594. }
  24595. serializeGeometry(geometry, serializationObject.geometries);
  24596. }
  24597. // Skeletons
  24598. if (mesh.skeleton) {
  24599. serializationObject.skeletons = serializationObject.skeletons || [];
  24600. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24601. }
  24602. //serialize the actual mesh
  24603. serializationObject.meshes = serializationObject.meshes || [];
  24604. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24605. }
  24606. };
  24607. var SceneSerializer = (function () {
  24608. function SceneSerializer() {
  24609. }
  24610. SceneSerializer.Serialize = function (scene) {
  24611. var serializationObject = {};
  24612. // Scene
  24613. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24614. serializationObject.autoClear = scene.autoClear;
  24615. serializationObject.clearColor = scene.clearColor.asArray();
  24616. serializationObject.ambientColor = scene.ambientColor.asArray();
  24617. serializationObject.gravity = scene.gravity.asArray();
  24618. // Fog
  24619. if (scene.fogMode && scene.fogMode !== 0) {
  24620. serializationObject.fogMode = scene.fogMode;
  24621. serializationObject.fogColor = scene.fogColor.asArray();
  24622. serializationObject.fogStart = scene.fogStart;
  24623. serializationObject.fogEnd = scene.fogEnd;
  24624. serializationObject.fogDensity = scene.fogDensity;
  24625. }
  24626. // Lights
  24627. serializationObject.lights = [];
  24628. var index;
  24629. var light;
  24630. for (index = 0; index < scene.lights.length; index++) {
  24631. light = scene.lights[index];
  24632. serializationObject.lights.push(serializeLight(light));
  24633. }
  24634. // Cameras
  24635. serializationObject.cameras = [];
  24636. for (index = 0; index < scene.cameras.length; index++) {
  24637. var camera = scene.cameras[index];
  24638. serializationObject.cameras.push(serializeCamera(camera));
  24639. }
  24640. if (scene.activeCamera) {
  24641. serializationObject.activeCameraID = scene.activeCamera.id;
  24642. }
  24643. // Materials
  24644. serializationObject.materials = [];
  24645. serializationObject.multiMaterials = [];
  24646. var material;
  24647. for (index = 0; index < scene.materials.length; index++) {
  24648. material = scene.materials[index];
  24649. serializationObject.materials.push(serializeMaterial(material));
  24650. }
  24651. // MultiMaterials
  24652. serializationObject.multiMaterials = [];
  24653. for (index = 0; index < scene.multiMaterials.length; index++) {
  24654. var multiMaterial = scene.multiMaterials[index];
  24655. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  24656. }
  24657. for (index = 0; index < scene.materials.length; index++) {
  24658. material = scene.materials[index];
  24659. if (material instanceof BABYLON.StandardMaterial) {
  24660. serializationObject.materials.push(serializeMaterial(material));
  24661. }
  24662. else if (material instanceof BABYLON.MultiMaterial) {
  24663. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24664. }
  24665. }
  24666. // Skeletons
  24667. serializationObject.skeletons = [];
  24668. for (index = 0; index < scene.skeletons.length; index++) {
  24669. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24670. }
  24671. // Geometries
  24672. serializationObject.geometries = {};
  24673. serializationObject.geometries.boxes = [];
  24674. serializationObject.geometries.spheres = [];
  24675. serializationObject.geometries.cylinders = [];
  24676. serializationObject.geometries.toruses = [];
  24677. serializationObject.geometries.grounds = [];
  24678. serializationObject.geometries.planes = [];
  24679. serializationObject.geometries.torusKnots = [];
  24680. serializationObject.geometries.vertexData = [];
  24681. serializedGeometries = [];
  24682. var geometries = scene.getGeometries();
  24683. for (index = 0; index < geometries.length; index++) {
  24684. var geometry = geometries[index];
  24685. if (geometry.isReady()) {
  24686. serializeGeometry(geometry, serializationObject.geometries);
  24687. }
  24688. }
  24689. // Meshes
  24690. serializationObject.meshes = [];
  24691. for (index = 0; index < scene.meshes.length; index++) {
  24692. var abstractMesh = scene.meshes[index];
  24693. if (abstractMesh instanceof BABYLON.Mesh) {
  24694. var mesh = abstractMesh;
  24695. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24696. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24697. }
  24698. }
  24699. }
  24700. // Particles Systems
  24701. serializationObject.particleSystems = [];
  24702. for (index = 0; index < scene.particleSystems.length; index++) {
  24703. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24704. }
  24705. // Lens flares
  24706. serializationObject.lensFlareSystems = [];
  24707. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24708. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24709. }
  24710. // Shadows
  24711. serializationObject.shadowGenerators = [];
  24712. for (index = 0; index < scene.lights.length; index++) {
  24713. light = scene.lights[index];
  24714. if (light.getShadowGenerator()) {
  24715. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24716. }
  24717. }
  24718. return serializationObject;
  24719. };
  24720. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24721. if (withParents === void 0) { withParents = false; }
  24722. if (withChildren === void 0) { withChildren = false; }
  24723. var serializationObject = {};
  24724. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24725. if (withParents || withChildren) {
  24726. //deliberate for loop! not for each, appended should be processed as well.
  24727. for (var i = 0; i < toSerialize.length; ++i) {
  24728. if (withChildren) {
  24729. toSerialize[i].getDescendants().forEach(function (node) {
  24730. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24731. toSerialize.push(node);
  24732. }
  24733. });
  24734. }
  24735. //make sure the array doesn't contain the object already
  24736. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24737. toSerialize.push(toSerialize[i].parent);
  24738. }
  24739. }
  24740. }
  24741. toSerialize.forEach(function (mesh) {
  24742. finalizeSingleMesh(mesh, serializationObject);
  24743. });
  24744. return serializationObject;
  24745. };
  24746. return SceneSerializer;
  24747. })();
  24748. BABYLON.SceneSerializer = SceneSerializer;
  24749. })(BABYLON || (BABYLON = {}));
  24750. var BABYLON;
  24751. (function (BABYLON) {
  24752. // Unique ID when we import meshes from Babylon to CSG
  24753. var currentCSGMeshId = 0;
  24754. // # class Vertex
  24755. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24756. // one to provide additional features like texture coordinates and vertex
  24757. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24758. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24759. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24760. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24761. // is not used anywhere else.
  24762. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24763. var Vertex = (function () {
  24764. function Vertex(pos, normal, uv) {
  24765. this.pos = pos;
  24766. this.normal = normal;
  24767. this.uv = uv;
  24768. }
  24769. Vertex.prototype.clone = function () {
  24770. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24771. };
  24772. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24773. // orientation of a polygon is flipped.
  24774. Vertex.prototype.flip = function () {
  24775. this.normal = this.normal.scale(-1);
  24776. };
  24777. // Create a new vertex between this vertex and `other` by linearly
  24778. // interpolating all properties using a parameter of `t`. Subclasses should
  24779. // override this to interpolate additional properties.
  24780. Vertex.prototype.interpolate = function (other, t) {
  24781. 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));
  24782. };
  24783. return Vertex;
  24784. })();
  24785. // # class Plane
  24786. // Represents a plane in 3D space.
  24787. var Plane = (function () {
  24788. function Plane(normal, w) {
  24789. this.normal = normal;
  24790. this.w = w;
  24791. }
  24792. Plane.FromPoints = function (a, b, c) {
  24793. var v0 = c.subtract(a);
  24794. var v1 = b.subtract(a);
  24795. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24796. return null;
  24797. }
  24798. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24799. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24800. };
  24801. Plane.prototype.clone = function () {
  24802. return new Plane(this.normal.clone(), this.w);
  24803. };
  24804. Plane.prototype.flip = function () {
  24805. this.normal.scaleInPlace(-1);
  24806. this.w = -this.w;
  24807. };
  24808. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24809. // fragments in the appropriate lists. Coplanar polygons go into either
  24810. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24811. // respect to this plane. Polygons in front or in back of this plane go into
  24812. // either `front` or `back`.
  24813. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24814. var COPLANAR = 0;
  24815. var FRONT = 1;
  24816. var BACK = 2;
  24817. var SPANNING = 3;
  24818. // Classify each point as well as the entire polygon into one of the above
  24819. // four classes.
  24820. var polygonType = 0;
  24821. var types = [];
  24822. for (var i = 0; i < polygon.vertices.length; i++) {
  24823. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24824. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24825. polygonType |= type;
  24826. types.push(type);
  24827. }
  24828. // Put the polygon in the correct list, splitting it when necessary.
  24829. switch (polygonType) {
  24830. case COPLANAR:
  24831. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24832. break;
  24833. case FRONT:
  24834. front.push(polygon);
  24835. break;
  24836. case BACK:
  24837. back.push(polygon);
  24838. break;
  24839. case SPANNING:
  24840. var f = [], b = [];
  24841. for (i = 0; i < polygon.vertices.length; i++) {
  24842. var j = (i + 1) % polygon.vertices.length;
  24843. var ti = types[i], tj = types[j];
  24844. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24845. if (ti != BACK)
  24846. f.push(vi);
  24847. if (ti != FRONT)
  24848. b.push(ti != BACK ? vi.clone() : vi);
  24849. if ((ti | tj) == SPANNING) {
  24850. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24851. var v = vi.interpolate(vj, t);
  24852. f.push(v);
  24853. b.push(v.clone());
  24854. }
  24855. }
  24856. if (f.length >= 3) {
  24857. var poly = new Polygon(f, polygon.shared);
  24858. if (poly.plane)
  24859. front.push(poly);
  24860. }
  24861. if (b.length >= 3) {
  24862. poly = new Polygon(b, polygon.shared);
  24863. if (poly.plane)
  24864. back.push(poly);
  24865. }
  24866. break;
  24867. }
  24868. };
  24869. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24870. // point is on the plane.
  24871. Plane.EPSILON = 1e-5;
  24872. return Plane;
  24873. })();
  24874. // # class Polygon
  24875. // Represents a convex polygon. The vertices used to initialize a polygon must
  24876. // be coplanar and form a convex loop.
  24877. //
  24878. // Each convex polygon has a `shared` property, which is shared between all
  24879. // polygons that are clones of each other or were split from the same polygon.
  24880. // This can be used to define per-polygon properties (such as surface color).
  24881. var Polygon = (function () {
  24882. function Polygon(vertices, shared) {
  24883. this.vertices = vertices;
  24884. this.shared = shared;
  24885. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24886. }
  24887. Polygon.prototype.clone = function () {
  24888. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24889. return new Polygon(vertices, this.shared);
  24890. };
  24891. Polygon.prototype.flip = function () {
  24892. this.vertices.reverse().map(function (v) { v.flip(); });
  24893. this.plane.flip();
  24894. };
  24895. return Polygon;
  24896. })();
  24897. // # class Node
  24898. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24899. // by picking a polygon to split along. That polygon (and all other coplanar
  24900. // polygons) are added directly to that node and the other polygons are added to
  24901. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24902. // no distinction between internal and leaf nodes.
  24903. var Node = (function () {
  24904. function Node(polygons) {
  24905. this.plane = null;
  24906. this.front = null;
  24907. this.back = null;
  24908. this.polygons = [];
  24909. if (polygons) {
  24910. this.build(polygons);
  24911. }
  24912. }
  24913. Node.prototype.clone = function () {
  24914. var node = new Node();
  24915. node.plane = this.plane && this.plane.clone();
  24916. node.front = this.front && this.front.clone();
  24917. node.back = this.back && this.back.clone();
  24918. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24919. return node;
  24920. };
  24921. // Convert solid space to empty space and empty space to solid space.
  24922. Node.prototype.invert = function () {
  24923. for (var i = 0; i < this.polygons.length; i++) {
  24924. this.polygons[i].flip();
  24925. }
  24926. if (this.plane) {
  24927. this.plane.flip();
  24928. }
  24929. if (this.front) {
  24930. this.front.invert();
  24931. }
  24932. if (this.back) {
  24933. this.back.invert();
  24934. }
  24935. var temp = this.front;
  24936. this.front = this.back;
  24937. this.back = temp;
  24938. };
  24939. // Recursively remove all polygons in `polygons` that are inside this BSP
  24940. // tree.
  24941. Node.prototype.clipPolygons = function (polygons) {
  24942. if (!this.plane)
  24943. return polygons.slice();
  24944. var front = [], back = [];
  24945. for (var i = 0; i < polygons.length; i++) {
  24946. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24947. }
  24948. if (this.front) {
  24949. front = this.front.clipPolygons(front);
  24950. }
  24951. if (this.back) {
  24952. back = this.back.clipPolygons(back);
  24953. }
  24954. else {
  24955. back = [];
  24956. }
  24957. return front.concat(back);
  24958. };
  24959. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24960. // `bsp`.
  24961. Node.prototype.clipTo = function (bsp) {
  24962. this.polygons = bsp.clipPolygons(this.polygons);
  24963. if (this.front)
  24964. this.front.clipTo(bsp);
  24965. if (this.back)
  24966. this.back.clipTo(bsp);
  24967. };
  24968. // Return a list of all polygons in this BSP tree.
  24969. Node.prototype.allPolygons = function () {
  24970. var polygons = this.polygons.slice();
  24971. if (this.front)
  24972. polygons = polygons.concat(this.front.allPolygons());
  24973. if (this.back)
  24974. polygons = polygons.concat(this.back.allPolygons());
  24975. return polygons;
  24976. };
  24977. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24978. // new polygons are filtered down to the bottom of the tree and become new
  24979. // nodes there. Each set of polygons is partitioned using the first polygon
  24980. // (no heuristic is used to pick a good split).
  24981. Node.prototype.build = function (polygons) {
  24982. if (!polygons.length)
  24983. return;
  24984. if (!this.plane)
  24985. this.plane = polygons[0].plane.clone();
  24986. var front = [], back = [];
  24987. for (var i = 0; i < polygons.length; i++) {
  24988. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24989. }
  24990. if (front.length) {
  24991. if (!this.front)
  24992. this.front = new Node();
  24993. this.front.build(front);
  24994. }
  24995. if (back.length) {
  24996. if (!this.back)
  24997. this.back = new Node();
  24998. this.back.build(back);
  24999. }
  25000. };
  25001. return Node;
  25002. })();
  25003. var CSG = (function () {
  25004. function CSG() {
  25005. this.polygons = new Array();
  25006. }
  25007. // Convert BABYLON.Mesh to BABYLON.CSG
  25008. CSG.FromMesh = function (mesh) {
  25009. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25010. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25011. if (mesh instanceof BABYLON.Mesh) {
  25012. mesh.computeWorldMatrix(true);
  25013. matrix = mesh.getWorldMatrix();
  25014. meshPosition = mesh.position.clone();
  25015. meshRotation = mesh.rotation.clone();
  25016. if (mesh.rotationQuaternion) {
  25017. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25018. }
  25019. meshScaling = mesh.scaling.clone();
  25020. }
  25021. else {
  25022. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25023. }
  25024. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25025. var subMeshes = mesh.subMeshes;
  25026. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25027. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25028. vertices = [];
  25029. for (var j = 0; j < 3; j++) {
  25030. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25031. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25032. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25033. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25034. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25035. vertex = new Vertex(position, normal, uv);
  25036. vertices.push(vertex);
  25037. }
  25038. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25039. // To handle the case of degenerated triangle
  25040. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25041. if (polygon.plane)
  25042. polygons.push(polygon);
  25043. }
  25044. }
  25045. var csg = CSG.FromPolygons(polygons);
  25046. csg.matrix = matrix;
  25047. csg.position = meshPosition;
  25048. csg.rotation = meshRotation;
  25049. csg.scaling = meshScaling;
  25050. csg.rotationQuaternion = meshRotationQuaternion;
  25051. currentCSGMeshId++;
  25052. return csg;
  25053. };
  25054. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25055. CSG.FromPolygons = function (polygons) {
  25056. var csg = new CSG();
  25057. csg.polygons = polygons;
  25058. return csg;
  25059. };
  25060. CSG.prototype.clone = function () {
  25061. var csg = new CSG();
  25062. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25063. csg.copyTransformAttributes(this);
  25064. return csg;
  25065. };
  25066. CSG.prototype.toPolygons = function () {
  25067. return this.polygons;
  25068. };
  25069. CSG.prototype.union = function (csg) {
  25070. var a = new Node(this.clone().polygons);
  25071. var b = new Node(csg.clone().polygons);
  25072. a.clipTo(b);
  25073. b.clipTo(a);
  25074. b.invert();
  25075. b.clipTo(a);
  25076. b.invert();
  25077. a.build(b.allPolygons());
  25078. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25079. };
  25080. CSG.prototype.unionInPlace = function (csg) {
  25081. var a = new Node(this.polygons);
  25082. var b = new Node(csg.polygons);
  25083. a.clipTo(b);
  25084. b.clipTo(a);
  25085. b.invert();
  25086. b.clipTo(a);
  25087. b.invert();
  25088. a.build(b.allPolygons());
  25089. this.polygons = a.allPolygons();
  25090. };
  25091. CSG.prototype.subtract = function (csg) {
  25092. var a = new Node(this.clone().polygons);
  25093. var b = new Node(csg.clone().polygons);
  25094. a.invert();
  25095. a.clipTo(b);
  25096. b.clipTo(a);
  25097. b.invert();
  25098. b.clipTo(a);
  25099. b.invert();
  25100. a.build(b.allPolygons());
  25101. a.invert();
  25102. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25103. };
  25104. CSG.prototype.subtractInPlace = function (csg) {
  25105. var a = new Node(this.polygons);
  25106. var b = new Node(csg.polygons);
  25107. a.invert();
  25108. a.clipTo(b);
  25109. b.clipTo(a);
  25110. b.invert();
  25111. b.clipTo(a);
  25112. b.invert();
  25113. a.build(b.allPolygons());
  25114. a.invert();
  25115. this.polygons = a.allPolygons();
  25116. };
  25117. CSG.prototype.intersect = function (csg) {
  25118. var a = new Node(this.clone().polygons);
  25119. var b = new Node(csg.clone().polygons);
  25120. a.invert();
  25121. b.clipTo(a);
  25122. b.invert();
  25123. a.clipTo(b);
  25124. b.clipTo(a);
  25125. a.build(b.allPolygons());
  25126. a.invert();
  25127. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25128. };
  25129. CSG.prototype.intersectInPlace = function (csg) {
  25130. var a = new Node(this.polygons);
  25131. var b = new Node(csg.polygons);
  25132. a.invert();
  25133. b.clipTo(a);
  25134. b.invert();
  25135. a.clipTo(b);
  25136. b.clipTo(a);
  25137. a.build(b.allPolygons());
  25138. a.invert();
  25139. this.polygons = a.allPolygons();
  25140. };
  25141. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25142. // not modified.
  25143. CSG.prototype.inverse = function () {
  25144. var csg = this.clone();
  25145. csg.inverseInPlace();
  25146. return csg;
  25147. };
  25148. CSG.prototype.inverseInPlace = function () {
  25149. this.polygons.map(function (p) { p.flip(); });
  25150. };
  25151. // This is used to keep meshes transformations so they can be restored
  25152. // when we build back a Babylon Mesh
  25153. // NB : All CSG operations are performed in world coordinates
  25154. CSG.prototype.copyTransformAttributes = function (csg) {
  25155. this.matrix = csg.matrix;
  25156. this.position = csg.position;
  25157. this.rotation = csg.rotation;
  25158. this.scaling = csg.scaling;
  25159. this.rotationQuaternion = csg.rotationQuaternion;
  25160. return this;
  25161. };
  25162. // Build Raw mesh from CSG
  25163. // Coordinates here are in world space
  25164. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25165. var matrix = this.matrix.clone();
  25166. matrix.invert();
  25167. 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;
  25168. if (keepSubMeshes) {
  25169. // Sort Polygons, since subMeshes are indices range
  25170. polygons.sort(function (a, b) {
  25171. if (a.shared.meshId === b.shared.meshId) {
  25172. return a.shared.subMeshId - b.shared.subMeshId;
  25173. }
  25174. else {
  25175. return a.shared.meshId - b.shared.meshId;
  25176. }
  25177. });
  25178. }
  25179. for (var i = 0, il = polygons.length; i < il; i++) {
  25180. polygon = polygons[i];
  25181. // Building SubMeshes
  25182. if (!subMesh_dict[polygon.shared.meshId]) {
  25183. subMesh_dict[polygon.shared.meshId] = {};
  25184. }
  25185. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25186. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25187. indexStart: +Infinity,
  25188. indexEnd: -Infinity,
  25189. materialIndex: polygon.shared.materialIndex
  25190. };
  25191. }
  25192. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25193. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25194. polygonIndices[0] = 0;
  25195. polygonIndices[1] = j - 1;
  25196. polygonIndices[2] = j;
  25197. for (var k = 0; k < 3; k++) {
  25198. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25199. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25200. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25201. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25202. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25203. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25204. // Check if 2 points can be merged
  25205. if (!(typeof vertex_idx !== 'undefined' &&
  25206. normals[vertex_idx * 3] === localNormal.x &&
  25207. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25208. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25209. uvs[vertex_idx * 2] === uv.x &&
  25210. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25211. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25212. uvs.push(uv.x, uv.y);
  25213. normals.push(normal.x, normal.y, normal.z);
  25214. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25215. }
  25216. indices.push(vertex_idx);
  25217. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25218. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25219. currentIndex++;
  25220. }
  25221. }
  25222. }
  25223. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25224. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25225. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25226. mesh.setIndices(indices);
  25227. if (keepSubMeshes) {
  25228. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25229. var materialIndexOffset = 0, materialMaxIndex;
  25230. mesh.subMeshes.length = 0;
  25231. for (var m in subMesh_dict) {
  25232. materialMaxIndex = -1;
  25233. for (var sm in subMesh_dict[m]) {
  25234. subMesh_obj = subMesh_dict[m][sm];
  25235. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25236. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25237. }
  25238. materialIndexOffset += ++materialMaxIndex;
  25239. }
  25240. }
  25241. return mesh;
  25242. };
  25243. // Build Mesh from CSG taking material and transforms into account
  25244. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25245. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25246. mesh.material = material;
  25247. mesh.position.copyFrom(this.position);
  25248. mesh.rotation.copyFrom(this.rotation);
  25249. if (this.rotationQuaternion) {
  25250. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25251. }
  25252. mesh.scaling.copyFrom(this.scaling);
  25253. mesh.computeWorldMatrix(true);
  25254. return mesh;
  25255. };
  25256. return CSG;
  25257. })();
  25258. BABYLON.CSG = CSG;
  25259. })(BABYLON || (BABYLON = {}));
  25260. var BABYLON;
  25261. (function (BABYLON) {
  25262. var VRDistortionCorrectionPostProcess = (function (_super) {
  25263. __extends(VRDistortionCorrectionPostProcess, _super);
  25264. //ANY
  25265. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25266. var _this = this;
  25267. _super.call(this, name, "vrDistortionCorrection", [
  25268. 'LensCenter',
  25269. 'Scale',
  25270. 'ScaleIn',
  25271. 'HmdWarpParam'
  25272. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25273. this._isRightEye = isRightEye;
  25274. this._distortionFactors = vrMetrics.distortionK;
  25275. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25276. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25277. this.onSizeChanged = function () {
  25278. _this.aspectRatio = _this.width * .5 / _this.height;
  25279. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25280. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25281. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25282. };
  25283. this.onApply = function (effect) {
  25284. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25285. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25286. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25287. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25288. };
  25289. }
  25290. return VRDistortionCorrectionPostProcess;
  25291. })(BABYLON.PostProcess);
  25292. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25293. })(BABYLON || (BABYLON = {}));
  25294. // Mainly based on these 2 articles :
  25295. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  25296. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25297. var BABYLON;
  25298. (function (BABYLON) {
  25299. (function (JoystickAxis) {
  25300. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25301. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25302. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25303. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25304. var JoystickAxis = BABYLON.JoystickAxis;
  25305. var VirtualJoystick = (function () {
  25306. function VirtualJoystick(leftJoystick) {
  25307. var _this = this;
  25308. if (leftJoystick) {
  25309. this._leftJoystick = true;
  25310. }
  25311. else {
  25312. this._leftJoystick = false;
  25313. }
  25314. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25315. VirtualJoystick._globalJoystickIndex++;
  25316. // By default left & right arrow keys are moving the X
  25317. // and up & down keys are moving the Y
  25318. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25319. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25320. this.reverseLeftRight = false;
  25321. this.reverseUpDown = false;
  25322. // collections of pointers
  25323. this._touches = new BABYLON.SmartCollection();
  25324. this.deltaPosition = BABYLON.Vector3.Zero();
  25325. this._joystickSensibility = 25;
  25326. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25327. this._rotationSpeed = 25;
  25328. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25329. this._rotateOnAxisRelativeToMesh = false;
  25330. this._onResize = function (evt) {
  25331. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25332. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25333. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25334. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25335. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25336. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25337. };
  25338. // injecting a canvas element on top of the canvas 3D game
  25339. if (!VirtualJoystick.vjCanvas) {
  25340. window.addEventListener("resize", this._onResize, false);
  25341. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25342. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25343. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25344. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25345. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25346. VirtualJoystick.vjCanvas.style.width = "100%";
  25347. VirtualJoystick.vjCanvas.style.height = "100%";
  25348. VirtualJoystick.vjCanvas.style.position = "absolute";
  25349. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25350. VirtualJoystick.vjCanvas.style.top = "0px";
  25351. VirtualJoystick.vjCanvas.style.left = "0px";
  25352. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25353. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25354. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25355. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25356. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25357. document.body.appendChild(VirtualJoystick.vjCanvas);
  25358. }
  25359. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25360. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25361. this.pressed = false;
  25362. // default joystick color
  25363. this._joystickColor = "cyan";
  25364. this._joystickPointerID = -1;
  25365. // current joystick position
  25366. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25367. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25368. // origin joystick position
  25369. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25370. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25371. this._onPointerDownHandlerRef = function (evt) {
  25372. _this._onPointerDown(evt);
  25373. };
  25374. this._onPointerMoveHandlerRef = function (evt) {
  25375. _this._onPointerMove(evt);
  25376. };
  25377. this._onPointerOutHandlerRef = function (evt) {
  25378. _this._onPointerUp(evt);
  25379. };
  25380. this._onPointerUpHandlerRef = function (evt) {
  25381. _this._onPointerUp(evt);
  25382. };
  25383. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25384. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25385. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25386. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25387. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25388. evt.preventDefault(); // Disables system menu
  25389. }, false);
  25390. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25391. }
  25392. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25393. this._joystickSensibility = newJoystickSensibility;
  25394. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25395. };
  25396. VirtualJoystick.prototype._onPointerDown = function (e) {
  25397. var positionOnScreenCondition;
  25398. e.preventDefault();
  25399. if (this._leftJoystick === true) {
  25400. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25401. }
  25402. else {
  25403. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25404. }
  25405. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25406. // First contact will be dedicated to the virtual joystick
  25407. this._joystickPointerID = e.pointerId;
  25408. this._joystickPointerStartPos.x = e.clientX;
  25409. this._joystickPointerStartPos.y = e.clientY;
  25410. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25411. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25412. this._deltaJoystickVector.x = 0;
  25413. this._deltaJoystickVector.y = 0;
  25414. this.pressed = true;
  25415. this._touches.add(e.pointerId.toString(), e);
  25416. }
  25417. else {
  25418. // You can only trigger the action buttons with a joystick declared
  25419. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25420. this._action();
  25421. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25422. }
  25423. }
  25424. };
  25425. VirtualJoystick.prototype._onPointerMove = function (e) {
  25426. // If the current pointer is the one associated to the joystick (first touch contact)
  25427. if (this._joystickPointerID == e.pointerId) {
  25428. this._joystickPointerPos.x = e.clientX;
  25429. this._joystickPointerPos.y = e.clientY;
  25430. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25431. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25432. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25433. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25434. switch (this._axisTargetedByLeftAndRight) {
  25435. case JoystickAxis.X:
  25436. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25437. break;
  25438. case JoystickAxis.Y:
  25439. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25440. break;
  25441. case JoystickAxis.Z:
  25442. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25443. break;
  25444. }
  25445. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25446. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25447. switch (this._axisTargetedByUpAndDown) {
  25448. case JoystickAxis.X:
  25449. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25450. break;
  25451. case JoystickAxis.Y:
  25452. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25453. break;
  25454. case JoystickAxis.Z:
  25455. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25456. break;
  25457. }
  25458. }
  25459. else {
  25460. if (this._touches.item(e.pointerId.toString())) {
  25461. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25462. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25463. }
  25464. }
  25465. };
  25466. VirtualJoystick.prototype._onPointerUp = function (e) {
  25467. if (this._joystickPointerID == e.pointerId) {
  25468. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25469. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25470. this._joystickPointerID = -1;
  25471. this.pressed = false;
  25472. }
  25473. else {
  25474. var touch = this._touches.item(e.pointerId.toString());
  25475. if (touch) {
  25476. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25477. }
  25478. }
  25479. this._deltaJoystickVector.x = 0;
  25480. this._deltaJoystickVector.y = 0;
  25481. this._touches.remove(e.pointerId.toString());
  25482. };
  25483. /**
  25484. * Change the color of the virtual joystick
  25485. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25486. */
  25487. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25488. this._joystickColor = newColor;
  25489. };
  25490. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25491. this._action = action;
  25492. };
  25493. // Define which axis you'd like to control for left & right
  25494. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25495. switch (axis) {
  25496. case JoystickAxis.X:
  25497. case JoystickAxis.Y:
  25498. case JoystickAxis.Z:
  25499. this._axisTargetedByLeftAndRight = axis;
  25500. break;
  25501. default:
  25502. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25503. break;
  25504. }
  25505. };
  25506. // Define which axis you'd like to control for up & down
  25507. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25508. switch (axis) {
  25509. case JoystickAxis.X:
  25510. case JoystickAxis.Y:
  25511. case JoystickAxis.Z:
  25512. this._axisTargetedByUpAndDown = axis;
  25513. break;
  25514. default:
  25515. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25516. break;
  25517. }
  25518. };
  25519. VirtualJoystick.prototype._clearCanvas = function () {
  25520. if (this._leftJoystick) {
  25521. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25522. }
  25523. else {
  25524. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25525. }
  25526. };
  25527. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25528. var _this = this;
  25529. if (this.pressed) {
  25530. this._touches.forEach(function (touch) {
  25531. if (touch.pointerId === _this._joystickPointerID) {
  25532. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25533. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25534. VirtualJoystick.vjCanvasContext.beginPath();
  25535. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25536. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25537. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25538. VirtualJoystick.vjCanvasContext.stroke();
  25539. VirtualJoystick.vjCanvasContext.closePath();
  25540. VirtualJoystick.vjCanvasContext.beginPath();
  25541. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25542. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25543. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25544. VirtualJoystick.vjCanvasContext.stroke();
  25545. VirtualJoystick.vjCanvasContext.closePath();
  25546. VirtualJoystick.vjCanvasContext.beginPath();
  25547. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25548. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25549. VirtualJoystick.vjCanvasContext.stroke();
  25550. VirtualJoystick.vjCanvasContext.closePath();
  25551. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25552. }
  25553. else {
  25554. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25555. VirtualJoystick.vjCanvasContext.beginPath();
  25556. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25557. VirtualJoystick.vjCanvasContext.beginPath();
  25558. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25559. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25560. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25561. VirtualJoystick.vjCanvasContext.stroke();
  25562. VirtualJoystick.vjCanvasContext.closePath();
  25563. touch.prevX = touch.x;
  25564. touch.prevY = touch.y;
  25565. }
  25566. ;
  25567. });
  25568. }
  25569. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25570. };
  25571. VirtualJoystick.prototype.releaseCanvas = function () {
  25572. if (VirtualJoystick.vjCanvas) {
  25573. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25574. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25575. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25576. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25577. window.removeEventListener("resize", this._onResize);
  25578. document.body.removeChild(VirtualJoystick.vjCanvas);
  25579. VirtualJoystick.vjCanvas = null;
  25580. }
  25581. };
  25582. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25583. VirtualJoystick._globalJoystickIndex = 0;
  25584. return VirtualJoystick;
  25585. })();
  25586. BABYLON.VirtualJoystick = VirtualJoystick;
  25587. })(BABYLON || (BABYLON = {}));
  25588. var BABYLON;
  25589. (function (BABYLON) {
  25590. // We're mainly based on the logic defined into the FreeCamera code
  25591. var VirtualJoysticksCamera = (function (_super) {
  25592. __extends(VirtualJoysticksCamera, _super);
  25593. function VirtualJoysticksCamera(name, position, scene) {
  25594. _super.call(this, name, position, scene);
  25595. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25596. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25597. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25598. this._leftjoystick.setJoystickSensibility(0.15);
  25599. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25600. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25601. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25602. this._rightjoystick.reverseUpDown = true;
  25603. this._rightjoystick.setJoystickSensibility(0.05);
  25604. this._rightjoystick.setJoystickColor("yellow");
  25605. }
  25606. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25607. return this._leftjoystick;
  25608. };
  25609. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25610. return this._rightjoystick;
  25611. };
  25612. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25613. var speed = this._computeLocalCameraSpeed() * 50;
  25614. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25615. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25616. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25617. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25618. if (!this._leftjoystick.pressed) {
  25619. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25620. }
  25621. if (!this._rightjoystick.pressed) {
  25622. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25623. }
  25624. _super.prototype._checkInputs.call(this);
  25625. };
  25626. VirtualJoysticksCamera.prototype.dispose = function () {
  25627. this._leftjoystick.releaseCanvas();
  25628. _super.prototype.dispose.call(this);
  25629. };
  25630. return VirtualJoysticksCamera;
  25631. })(BABYLON.FreeCamera);
  25632. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25633. })(BABYLON || (BABYLON = {}));
  25634. var BABYLON;
  25635. (function (BABYLON) {
  25636. var ShaderMaterial = (function (_super) {
  25637. __extends(ShaderMaterial, _super);
  25638. function ShaderMaterial(name, scene, shaderPath, options) {
  25639. _super.call(this, name, scene);
  25640. this._textures = new Array();
  25641. this._floats = new Array();
  25642. this._floatsArrays = {};
  25643. this._colors3 = new Array();
  25644. this._colors4 = new Array();
  25645. this._vectors2 = new Array();
  25646. this._vectors3 = new Array();
  25647. this._vectors4 = new Array();
  25648. this._matrices = new Array();
  25649. this._matrices3x3 = new Array();
  25650. this._matrices2x2 = new Array();
  25651. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25652. this._shaderPath = shaderPath;
  25653. options.needAlphaBlending = options.needAlphaBlending || false;
  25654. options.needAlphaTesting = options.needAlphaTesting || false;
  25655. options.attributes = options.attributes || ["position", "normal", "uv"];
  25656. options.uniforms = options.uniforms || ["worldViewProjection"];
  25657. options.samplers = options.samplers || [];
  25658. options.defines = options.defines || [];
  25659. this._options = options;
  25660. }
  25661. ShaderMaterial.prototype.needAlphaBlending = function () {
  25662. return this._options.needAlphaBlending;
  25663. };
  25664. ShaderMaterial.prototype.needAlphaTesting = function () {
  25665. return this._options.needAlphaTesting;
  25666. };
  25667. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25668. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25669. this._options.uniforms.push(uniformName);
  25670. }
  25671. };
  25672. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25673. if (this._options.samplers.indexOf(name) === -1) {
  25674. this._options.samplers.push(name);
  25675. }
  25676. this._textures[name] = texture;
  25677. return this;
  25678. };
  25679. ShaderMaterial.prototype.setFloat = function (name, value) {
  25680. this._checkUniform(name);
  25681. this._floats[name] = value;
  25682. return this;
  25683. };
  25684. ShaderMaterial.prototype.setFloats = function (name, value) {
  25685. this._checkUniform(name);
  25686. this._floatsArrays[name] = value;
  25687. return this;
  25688. };
  25689. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25690. this._checkUniform(name);
  25691. this._colors3[name] = value;
  25692. return this;
  25693. };
  25694. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25695. this._checkUniform(name);
  25696. this._colors4[name] = value;
  25697. return this;
  25698. };
  25699. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25700. this._checkUniform(name);
  25701. this._vectors2[name] = value;
  25702. return this;
  25703. };
  25704. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25705. this._checkUniform(name);
  25706. this._vectors3[name] = value;
  25707. return this;
  25708. };
  25709. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25710. this._checkUniform(name);
  25711. this._vectors4[name] = value;
  25712. return this;
  25713. };
  25714. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25715. this._checkUniform(name);
  25716. this._matrices[name] = value;
  25717. return this;
  25718. };
  25719. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25720. this._checkUniform(name);
  25721. this._matrices3x3[name] = value;
  25722. return this;
  25723. };
  25724. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25725. this._checkUniform(name);
  25726. this._matrices2x2[name] = value;
  25727. return this;
  25728. };
  25729. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25730. var scene = this.getScene();
  25731. var engine = scene.getEngine();
  25732. if (!this.checkReadyOnEveryCall) {
  25733. if (this._renderId === scene.getRenderId()) {
  25734. return true;
  25735. }
  25736. }
  25737. // Instances
  25738. var defines = [];
  25739. var fallbacks = new BABYLON.EffectFallbacks();
  25740. if (useInstances) {
  25741. defines.push("#define INSTANCES");
  25742. }
  25743. for (var index = 0; index < this._options.defines.length; index++) {
  25744. defines.push(this._options.defines[index]);
  25745. }
  25746. // Bones
  25747. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25748. defines.push("#define BONES");
  25749. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25750. defines.push("#define BONES4");
  25751. fallbacks.addFallback(0, "BONES4");
  25752. }
  25753. // Alpha test
  25754. if (engine.getAlphaTesting()) {
  25755. defines.push("#define ALPHATEST");
  25756. }
  25757. var previousEffect = this._effect;
  25758. var join = defines.join("\n");
  25759. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25760. if (!this._effect.isReady()) {
  25761. return false;
  25762. }
  25763. if (previousEffect !== this._effect) {
  25764. scene.resetCachedMaterial();
  25765. }
  25766. this._renderId = scene.getRenderId();
  25767. return true;
  25768. };
  25769. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25770. var scene = this.getScene();
  25771. if (this._options.uniforms.indexOf("world") !== -1) {
  25772. this._effect.setMatrix("world", world);
  25773. }
  25774. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25775. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25776. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25777. }
  25778. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25779. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25780. }
  25781. };
  25782. ShaderMaterial.prototype.bind = function (world, mesh) {
  25783. // Std values
  25784. this.bindOnlyWorldMatrix(world);
  25785. if (this.getScene().getCachedMaterial() !== this) {
  25786. if (this._options.uniforms.indexOf("view") !== -1) {
  25787. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25788. }
  25789. if (this._options.uniforms.indexOf("projection") !== -1) {
  25790. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25791. }
  25792. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25793. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25794. }
  25795. // Bones
  25796. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25797. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25798. }
  25799. // Texture
  25800. for (var name in this._textures) {
  25801. this._effect.setTexture(name, this._textures[name]);
  25802. }
  25803. // Float
  25804. for (name in this._floats) {
  25805. this._effect.setFloat(name, this._floats[name]);
  25806. }
  25807. // Float s
  25808. for (name in this._floatsArrays) {
  25809. this._effect.setArray(name, this._floatsArrays[name]);
  25810. }
  25811. // Color3
  25812. for (name in this._colors3) {
  25813. this._effect.setColor3(name, this._colors3[name]);
  25814. }
  25815. // Color4
  25816. for (name in this._colors4) {
  25817. var color = this._colors4[name];
  25818. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25819. }
  25820. // Vector2
  25821. for (name in this._vectors2) {
  25822. this._effect.setVector2(name, this._vectors2[name]);
  25823. }
  25824. // Vector3
  25825. for (name in this._vectors3) {
  25826. this._effect.setVector3(name, this._vectors3[name]);
  25827. }
  25828. // Vector4
  25829. for (name in this._vectors4) {
  25830. this._effect.setVector4(name, this._vectors4[name]);
  25831. }
  25832. // Matrix
  25833. for (name in this._matrices) {
  25834. this._effect.setMatrix(name, this._matrices[name]);
  25835. }
  25836. // Matrix 3x3
  25837. for (name in this._matrices3x3) {
  25838. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25839. }
  25840. // Matrix 2x2
  25841. for (name in this._matrices2x2) {
  25842. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25843. }
  25844. }
  25845. _super.prototype.bind.call(this, world, mesh);
  25846. };
  25847. ShaderMaterial.prototype.clone = function (name) {
  25848. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25849. return newShaderMaterial;
  25850. };
  25851. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25852. for (var name in this._textures) {
  25853. this._textures[name].dispose();
  25854. }
  25855. this._textures = [];
  25856. _super.prototype.dispose.call(this, forceDisposeEffect);
  25857. };
  25858. return ShaderMaterial;
  25859. })(BABYLON.Material);
  25860. BABYLON.ShaderMaterial = ShaderMaterial;
  25861. })(BABYLON || (BABYLON = {}));
  25862. var BABYLON;
  25863. (function (BABYLON) {
  25864. var VertexData = (function () {
  25865. function VertexData() {
  25866. }
  25867. VertexData.prototype.set = function (data, kind) {
  25868. switch (kind) {
  25869. case BABYLON.VertexBuffer.PositionKind:
  25870. this.positions = data;
  25871. break;
  25872. case BABYLON.VertexBuffer.NormalKind:
  25873. this.normals = data;
  25874. break;
  25875. case BABYLON.VertexBuffer.UVKind:
  25876. this.uvs = data;
  25877. break;
  25878. case BABYLON.VertexBuffer.UV2Kind:
  25879. this.uvs2 = data;
  25880. break;
  25881. case BABYLON.VertexBuffer.UV3Kind:
  25882. this.uvs3 = data;
  25883. break;
  25884. case BABYLON.VertexBuffer.UV4Kind:
  25885. this.uvs4 = data;
  25886. break;
  25887. case BABYLON.VertexBuffer.UV5Kind:
  25888. this.uvs5 = data;
  25889. break;
  25890. case BABYLON.VertexBuffer.UV6Kind:
  25891. this.uvs6 = data;
  25892. break;
  25893. case BABYLON.VertexBuffer.ColorKind:
  25894. this.colors = data;
  25895. break;
  25896. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25897. this.matricesIndices = data;
  25898. break;
  25899. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25900. this.matricesWeights = data;
  25901. break;
  25902. }
  25903. };
  25904. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25905. this._applyTo(mesh, updatable);
  25906. };
  25907. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25908. this._applyTo(geometry, updatable);
  25909. };
  25910. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25911. this._update(mesh);
  25912. };
  25913. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25914. this._update(geometry);
  25915. };
  25916. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25917. if (this.positions) {
  25918. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25919. }
  25920. if (this.normals) {
  25921. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25922. }
  25923. if (this.uvs) {
  25924. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25925. }
  25926. if (this.uvs2) {
  25927. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25928. }
  25929. if (this.uvs3) {
  25930. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25931. }
  25932. if (this.uvs4) {
  25933. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25934. }
  25935. if (this.uvs5) {
  25936. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25937. }
  25938. if (this.uvs6) {
  25939. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25940. }
  25941. if (this.colors) {
  25942. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25943. }
  25944. if (this.matricesIndices) {
  25945. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25946. }
  25947. if (this.matricesWeights) {
  25948. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25949. }
  25950. if (this.indices) {
  25951. meshOrGeometry.setIndices(this.indices);
  25952. }
  25953. };
  25954. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25955. if (this.positions) {
  25956. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25957. }
  25958. if (this.normals) {
  25959. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25960. }
  25961. if (this.uvs) {
  25962. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25963. }
  25964. if (this.uvs2) {
  25965. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25966. }
  25967. if (this.uvs3) {
  25968. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25969. }
  25970. if (this.uvs4) {
  25971. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25972. }
  25973. if (this.uvs5) {
  25974. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25975. }
  25976. if (this.uvs6) {
  25977. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25978. }
  25979. if (this.colors) {
  25980. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25981. }
  25982. if (this.matricesIndices) {
  25983. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25984. }
  25985. if (this.matricesWeights) {
  25986. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25987. }
  25988. if (this.indices) {
  25989. meshOrGeometry.setIndices(this.indices);
  25990. }
  25991. };
  25992. VertexData.prototype.transform = function (matrix) {
  25993. var transformed = BABYLON.Vector3.Zero();
  25994. var index;
  25995. if (this.positions) {
  25996. var position = BABYLON.Vector3.Zero();
  25997. for (index = 0; index < this.positions.length; index += 3) {
  25998. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25999. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26000. this.positions[index] = transformed.x;
  26001. this.positions[index + 1] = transformed.y;
  26002. this.positions[index + 2] = transformed.z;
  26003. }
  26004. }
  26005. if (this.normals) {
  26006. var normal = BABYLON.Vector3.Zero();
  26007. for (index = 0; index < this.normals.length; index += 3) {
  26008. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26009. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26010. this.normals[index] = transformed.x;
  26011. this.normals[index + 1] = transformed.y;
  26012. this.normals[index + 2] = transformed.z;
  26013. }
  26014. }
  26015. };
  26016. VertexData.prototype.merge = function (other) {
  26017. var index;
  26018. if (other.indices) {
  26019. if (!this.indices) {
  26020. this.indices = [];
  26021. }
  26022. var offset = this.positions ? this.positions.length / 3 : 0;
  26023. for (index = 0; index < other.indices.length; index++) {
  26024. this.indices.push(other.indices[index] + offset);
  26025. }
  26026. }
  26027. if (other.positions) {
  26028. if (!this.positions) {
  26029. this.positions = [];
  26030. }
  26031. for (index = 0; index < other.positions.length; index++) {
  26032. this.positions.push(other.positions[index]);
  26033. }
  26034. }
  26035. if (other.normals) {
  26036. if (!this.normals) {
  26037. this.normals = [];
  26038. }
  26039. for (index = 0; index < other.normals.length; index++) {
  26040. this.normals.push(other.normals[index]);
  26041. }
  26042. }
  26043. if (other.uvs) {
  26044. if (!this.uvs) {
  26045. this.uvs = [];
  26046. }
  26047. for (index = 0; index < other.uvs.length; index++) {
  26048. this.uvs.push(other.uvs[index]);
  26049. }
  26050. }
  26051. if (other.uvs2) {
  26052. if (!this.uvs2) {
  26053. this.uvs2 = [];
  26054. }
  26055. for (index = 0; index < other.uvs2.length; index++) {
  26056. this.uvs2.push(other.uvs2[index]);
  26057. }
  26058. }
  26059. if (other.uvs3) {
  26060. if (!this.uvs3) {
  26061. this.uvs3 = [];
  26062. }
  26063. for (index = 0; index < other.uvs3.length; index++) {
  26064. this.uvs3.push(other.uvs3[index]);
  26065. }
  26066. }
  26067. if (other.uvs4) {
  26068. if (!this.uvs4) {
  26069. this.uvs4 = [];
  26070. }
  26071. for (index = 0; index < other.uvs4.length; index++) {
  26072. this.uvs4.push(other.uvs4[index]);
  26073. }
  26074. }
  26075. if (other.uvs5) {
  26076. if (!this.uvs5) {
  26077. this.uvs5 = [];
  26078. }
  26079. for (index = 0; index < other.uvs5.length; index++) {
  26080. this.uvs5.push(other.uvs5[index]);
  26081. }
  26082. }
  26083. if (other.uvs6) {
  26084. if (!this.uvs6) {
  26085. this.uvs6 = [];
  26086. }
  26087. for (index = 0; index < other.uvs6.length; index++) {
  26088. this.uvs6.push(other.uvs6[index]);
  26089. }
  26090. }
  26091. if (other.matricesIndices) {
  26092. if (!this.matricesIndices) {
  26093. this.matricesIndices = [];
  26094. }
  26095. for (index = 0; index < other.matricesIndices.length; index++) {
  26096. this.matricesIndices.push(other.matricesIndices[index]);
  26097. }
  26098. }
  26099. if (other.matricesWeights) {
  26100. if (!this.matricesWeights) {
  26101. this.matricesWeights = [];
  26102. }
  26103. for (index = 0; index < other.matricesWeights.length; index++) {
  26104. this.matricesWeights.push(other.matricesWeights[index]);
  26105. }
  26106. }
  26107. if (other.colors) {
  26108. if (!this.colors) {
  26109. this.colors = [];
  26110. }
  26111. for (index = 0; index < other.colors.length; index++) {
  26112. this.colors.push(other.colors[index]);
  26113. }
  26114. }
  26115. };
  26116. // Statics
  26117. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26118. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26119. };
  26120. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26121. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26122. };
  26123. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26124. var result = new VertexData();
  26125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26126. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26127. }
  26128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26129. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26130. }
  26131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26132. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26133. }
  26134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26135. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26136. }
  26137. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26138. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26139. }
  26140. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26141. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26142. }
  26143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26144. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26145. }
  26146. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26147. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26148. }
  26149. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26150. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26151. }
  26152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26153. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26154. }
  26155. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26156. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26157. }
  26158. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26159. return result;
  26160. };
  26161. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26162. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26163. closeArray = closeArray || false;
  26164. closePath = closePath || false;
  26165. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26166. offset = offset || defaultOffset;
  26167. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26168. var positions = [];
  26169. var indices = [];
  26170. var normals = [];
  26171. var uvs = [];
  26172. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26173. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26174. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26175. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26176. var minlg; // minimal length among all paths from pathArray
  26177. var lg = []; // array of path lengths : nb of vertex per path
  26178. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26179. var p; // path iterator
  26180. var i; // point iterator
  26181. var j; // point iterator
  26182. // if single path in pathArray
  26183. if (pathArray.length < 2) {
  26184. var ar1 = [];
  26185. var ar2 = [];
  26186. for (i = 0; i < pathArray[0].length - offset; i++) {
  26187. ar1.push(pathArray[0][i]);
  26188. ar2.push(pathArray[0][i + offset]);
  26189. }
  26190. pathArray = [ar1, ar2];
  26191. }
  26192. // positions and horizontal distances (u)
  26193. var idc = 0;
  26194. var closePathCorr = (closePath) ? 1 : 0;
  26195. var path;
  26196. var l;
  26197. minlg = pathArray[0].length;
  26198. var vectlg;
  26199. var dist;
  26200. for (p = 0; p < pathArray.length; p++) {
  26201. uTotalDistance[p] = 0;
  26202. us[p] = [0];
  26203. path = pathArray[p];
  26204. l = path.length;
  26205. minlg = (minlg < l) ? minlg : l;
  26206. j = 0;
  26207. while (j < l) {
  26208. positions.push(path[j].x, path[j].y, path[j].z);
  26209. if (j > 0) {
  26210. vectlg = path[j].subtract(path[j - 1]).length();
  26211. dist = vectlg + uTotalDistance[p];
  26212. us[p].push(dist);
  26213. uTotalDistance[p] = dist;
  26214. }
  26215. j++;
  26216. }
  26217. if (closePath) {
  26218. j--;
  26219. positions.push(path[0].x, path[0].y, path[0].z);
  26220. vectlg = path[j].subtract(path[0]).length();
  26221. dist = vectlg + uTotalDistance[p];
  26222. us[p].push(dist);
  26223. uTotalDistance[p] = dist;
  26224. }
  26225. lg[p] = l + closePathCorr;
  26226. idx[p] = idc;
  26227. idc += (l + closePathCorr);
  26228. }
  26229. // vertical distances (v)
  26230. var path1;
  26231. var path2;
  26232. var vertex1;
  26233. var vertex2;
  26234. for (i = 0; i < minlg + closePathCorr; i++) {
  26235. vTotalDistance[i] = 0;
  26236. vs[i] = [0];
  26237. for (p = 0; p < pathArray.length - 1; p++) {
  26238. path1 = pathArray[p];
  26239. path2 = pathArray[p + 1];
  26240. if (i === minlg) {
  26241. vertex1 = path1[0];
  26242. vertex2 = path2[0];
  26243. }
  26244. else {
  26245. vertex1 = path1[i];
  26246. vertex2 = path2[i];
  26247. }
  26248. vectlg = vertex2.subtract(vertex1).length();
  26249. dist = vectlg + vTotalDistance[i];
  26250. vs[i].push(dist);
  26251. vTotalDistance[i] = dist;
  26252. }
  26253. if (closeArray) {
  26254. path1 = pathArray[p];
  26255. path2 = pathArray[0];
  26256. vectlg = path2[i].subtract(path1[i]).length();
  26257. dist = vectlg + vTotalDistance[i];
  26258. vTotalDistance[i] = dist;
  26259. }
  26260. }
  26261. // uvs
  26262. var u;
  26263. var v;
  26264. for (p = 0; p < pathArray.length; p++) {
  26265. for (i = 0; i < minlg + closePathCorr; i++) {
  26266. u = us[p][i] / uTotalDistance[p];
  26267. v = vs[i][p] / vTotalDistance[i];
  26268. uvs.push(u, v);
  26269. }
  26270. }
  26271. // indices
  26272. p = 0; // path index
  26273. var pi = 0; // positions array index
  26274. var l1 = lg[p] - 1; // path1 length
  26275. var l2 = lg[p + 1] - 1; // path2 length
  26276. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26277. var shft = idx[1] - idx[0]; // shift
  26278. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26279. while (pi <= min && p < path1nb) {
  26280. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  26281. indices.push(pi, pi + shft, pi + 1);
  26282. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26283. pi += 1;
  26284. if (pi === min) {
  26285. p++;
  26286. if (p === lg.length - 1) {
  26287. shft = idx[0] - idx[p];
  26288. l1 = lg[p] - 1;
  26289. l2 = lg[0] - 1;
  26290. }
  26291. else {
  26292. shft = idx[p + 1] - idx[p];
  26293. l1 = lg[p] - 1;
  26294. l2 = lg[p + 1] - 1;
  26295. }
  26296. pi = idx[p];
  26297. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26298. }
  26299. }
  26300. // normals
  26301. VertexData.ComputeNormals(positions, indices, normals);
  26302. if (closePath) {
  26303. var indexFirst = 0;
  26304. var indexLast = 0;
  26305. for (p = 0; p < pathArray.length; p++) {
  26306. indexFirst = idx[p] * 3;
  26307. if (p + 1 < pathArray.length) {
  26308. indexLast = (idx[p + 1] - 1) * 3;
  26309. }
  26310. else {
  26311. indexLast = normals.length - 3;
  26312. }
  26313. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26314. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26315. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26316. normals[indexLast] = normals[indexFirst];
  26317. normals[indexLast + 1] = normals[indexFirst + 1];
  26318. normals[indexLast + 2] = normals[indexFirst + 2];
  26319. }
  26320. }
  26321. // sides
  26322. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26323. // Result
  26324. var vertexData = new VertexData();
  26325. vertexData.indices = indices;
  26326. vertexData.positions = positions;
  26327. vertexData.normals = normals;
  26328. vertexData.uvs = uvs;
  26329. if (closePath) {
  26330. vertexData._idx = idx;
  26331. }
  26332. return vertexData;
  26333. };
  26334. VertexData.CreateBox = function (options, sideOrientation) {
  26335. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26336. var normalsSource = [
  26337. new BABYLON.Vector3(0, 0, 1),
  26338. new BABYLON.Vector3(0, 0, -1),
  26339. new BABYLON.Vector3(1, 0, 0),
  26340. new BABYLON.Vector3(-1, 0, 0),
  26341. new BABYLON.Vector3(0, 1, 0),
  26342. new BABYLON.Vector3(0, -1, 0)
  26343. ];
  26344. var indices = [];
  26345. var positions = [];
  26346. var normals = [];
  26347. var uvs = [];
  26348. var width = 1;
  26349. var height = 1;
  26350. var depth = 1;
  26351. if (options.width !== undefined) {
  26352. width = options.width || 1;
  26353. height = options.height || 1;
  26354. depth = options.depth || 1;
  26355. }
  26356. else {
  26357. width = options || 1;
  26358. height = options || 1;
  26359. depth = options || 1;
  26360. }
  26361. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26362. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26363. // Create each face in turn.
  26364. for (var index = 0; index < normalsSource.length; index++) {
  26365. var normal = normalsSource[index];
  26366. // Get two vectors perpendicular to the face normal and to each other.
  26367. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26368. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26369. // Six indices (two triangles) per face.
  26370. var verticesLength = positions.length / 3;
  26371. indices.push(verticesLength);
  26372. indices.push(verticesLength + 1);
  26373. indices.push(verticesLength + 2);
  26374. indices.push(verticesLength);
  26375. indices.push(verticesLength + 2);
  26376. indices.push(verticesLength + 3);
  26377. // Four vertices per face.
  26378. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26379. positions.push(vertex.x, vertex.y, vertex.z);
  26380. normals.push(normal.x, normal.y, normal.z);
  26381. uvs.push(1.0, 1.0);
  26382. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26383. positions.push(vertex.x, vertex.y, vertex.z);
  26384. normals.push(normal.x, normal.y, normal.z);
  26385. uvs.push(0.0, 1.0);
  26386. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26387. positions.push(vertex.x, vertex.y, vertex.z);
  26388. normals.push(normal.x, normal.y, normal.z);
  26389. uvs.push(0.0, 0.0);
  26390. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26391. positions.push(vertex.x, vertex.y, vertex.z);
  26392. normals.push(normal.x, normal.y, normal.z);
  26393. uvs.push(1.0, 0.0);
  26394. }
  26395. // sides
  26396. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26397. // Result
  26398. var vertexData = new VertexData();
  26399. vertexData.indices = indices;
  26400. vertexData.positions = positions;
  26401. vertexData.normals = normals;
  26402. vertexData.uvs = uvs;
  26403. return vertexData;
  26404. };
  26405. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26406. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26407. var segments;
  26408. var diameterX;
  26409. var diameterY;
  26410. var diameterZ;
  26411. if (options.segments) {
  26412. segments = options.segments || 32;
  26413. diameterX = options.diameterX || 1;
  26414. diameterY = options.diameterY || 1;
  26415. diameterZ = options.diameterZ || 1;
  26416. }
  26417. else {
  26418. segments = options || 32;
  26419. diameterX = diameter || 1;
  26420. diameterY = diameterX;
  26421. diameterZ = diameterX;
  26422. }
  26423. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26424. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26425. var totalZRotationSteps = 2 + segments;
  26426. var totalYRotationSteps = 2 * totalZRotationSteps;
  26427. var indices = [];
  26428. var positions = [];
  26429. var normals = [];
  26430. var uvs = [];
  26431. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26432. var normalizedZ = zRotationStep / totalZRotationSteps;
  26433. var angleZ = (normalizedZ * Math.PI);
  26434. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26435. var normalizedY = yRotationStep / totalYRotationSteps;
  26436. var angleY = normalizedY * Math.PI * 2;
  26437. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26438. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26439. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26440. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26441. var vertex = complete.multiply(radius);
  26442. var normal = BABYLON.Vector3.Normalize(vertex);
  26443. positions.push(vertex.x, vertex.y, vertex.z);
  26444. normals.push(normal.x, normal.y, normal.z);
  26445. uvs.push(normalizedZ, normalizedY);
  26446. }
  26447. if (zRotationStep > 0) {
  26448. var verticesCount = positions.length / 3;
  26449. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26450. indices.push((firstIndex));
  26451. indices.push((firstIndex + 1));
  26452. indices.push(firstIndex + totalYRotationSteps + 1);
  26453. indices.push((firstIndex + totalYRotationSteps + 1));
  26454. indices.push((firstIndex + 1));
  26455. indices.push((firstIndex + totalYRotationSteps + 2));
  26456. }
  26457. }
  26458. }
  26459. // Sides
  26460. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26461. // Result
  26462. var vertexData = new VertexData();
  26463. vertexData.indices = indices;
  26464. vertexData.positions = positions;
  26465. vertexData.normals = normals;
  26466. vertexData.uvs = uvs;
  26467. return vertexData;
  26468. };
  26469. // Cylinder and cone (made using ribbons)
  26470. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26471. if (subdivisions === void 0) { subdivisions = 1; }
  26472. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26473. var indices = [];
  26474. var positions = [];
  26475. var normals = [];
  26476. var uvs = [];
  26477. var angle_step = Math.PI * 2 / tessellation;
  26478. var angle;
  26479. var h;
  26480. var radius;
  26481. var tan = (diameterBottom - diameterTop) / 2 / height;
  26482. var ringVertex = BABYLON.Vector3.Zero();
  26483. var ringNormal = BABYLON.Vector3.Zero();
  26484. // positions, normals, uvs
  26485. var i;
  26486. var j;
  26487. for (i = 0; i <= subdivisions; i++) {
  26488. h = i / subdivisions;
  26489. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26490. for (j = 0; j <= tessellation; j++) {
  26491. angle = j * angle_step;
  26492. ringVertex.x = Math.cos(-angle) * radius;
  26493. ringVertex.y = -height / 2 + h * height;
  26494. ringVertex.z = Math.sin(-angle) * radius;
  26495. if (diameterTop === 0 && i === subdivisions) {
  26496. // if no top cap, reuse former normals
  26497. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26498. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26499. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26500. }
  26501. else {
  26502. ringNormal.x = ringVertex.x;
  26503. ringNormal.z = ringVertex.z;
  26504. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26505. ringNormal.normalize();
  26506. }
  26507. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26508. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26509. uvs.push(j / tessellation, 1 - h);
  26510. }
  26511. }
  26512. // indices
  26513. for (i = 0; i < subdivisions; i++) {
  26514. for (j = 0; j < tessellation; j++) {
  26515. var i0 = i * (tessellation + 1) + j;
  26516. var i1 = (i + 1) * (tessellation + 1) + j;
  26517. var i2 = i * (tessellation + 1) + (j + 1);
  26518. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26519. indices.push(i0, i1, i2);
  26520. indices.push(i3, i2, i1);
  26521. }
  26522. }
  26523. // Caps
  26524. var createCylinderCap = function (isTop) {
  26525. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26526. if (radius === 0) {
  26527. return;
  26528. }
  26529. var vbase = positions.length / 3;
  26530. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26531. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26532. // Cap positions, normals & uvs
  26533. var angle;
  26534. var circleVector;
  26535. var i;
  26536. for (i = 0; i < tessellation; i++) {
  26537. angle = Math.PI * 2 * i / tessellation;
  26538. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26539. var position = circleVector.scale(radius).add(offset);
  26540. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26541. positions.push(position.x, position.y, position.z);
  26542. normals.push(0, isTop ? 1 : -1, 0);
  26543. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26544. }
  26545. // Cap indices
  26546. for (i = 0; i < tessellation - 2; i++) {
  26547. if (!isTop) {
  26548. indices.push(vbase);
  26549. indices.push(vbase + (i + 1) % tessellation);
  26550. indices.push(vbase + (i + 2) % tessellation);
  26551. }
  26552. else {
  26553. indices.push(vbase);
  26554. indices.push(vbase + (i + 2) % tessellation);
  26555. indices.push(vbase + (i + 1) % tessellation);
  26556. }
  26557. }
  26558. };
  26559. // add caps to geometry
  26560. createCylinderCap(true);
  26561. createCylinderCap(false);
  26562. // Sides
  26563. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26564. var vertexData = new VertexData();
  26565. vertexData.indices = indices;
  26566. vertexData.positions = positions;
  26567. vertexData.normals = normals;
  26568. vertexData.uvs = uvs;
  26569. return vertexData;
  26570. };
  26571. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26572. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26573. var indices = [];
  26574. var positions = [];
  26575. var normals = [];
  26576. var uvs = [];
  26577. diameter = diameter || 1;
  26578. thickness = thickness || 0.5;
  26579. tessellation = tessellation || 16;
  26580. var stride = tessellation + 1;
  26581. for (var i = 0; i <= tessellation; i++) {
  26582. var u = i / tessellation;
  26583. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26584. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26585. for (var j = 0; j <= tessellation; j++) {
  26586. var v = 1 - j / tessellation;
  26587. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26588. var dx = Math.cos(innerAngle);
  26589. var dy = Math.sin(innerAngle);
  26590. // Create a vertex.
  26591. var normal = new BABYLON.Vector3(dx, dy, 0);
  26592. var position = normal.scale(thickness / 2);
  26593. var textureCoordinate = new BABYLON.Vector2(u, v);
  26594. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26595. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26596. positions.push(position.x, position.y, position.z);
  26597. normals.push(normal.x, normal.y, normal.z);
  26598. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26599. // And create indices for two triangles.
  26600. var nextI = (i + 1) % stride;
  26601. var nextJ = (j + 1) % stride;
  26602. indices.push(i * stride + j);
  26603. indices.push(i * stride + nextJ);
  26604. indices.push(nextI * stride + j);
  26605. indices.push(i * stride + nextJ);
  26606. indices.push(nextI * stride + nextJ);
  26607. indices.push(nextI * stride + j);
  26608. }
  26609. }
  26610. // Sides
  26611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26612. // Result
  26613. var vertexData = new VertexData();
  26614. vertexData.indices = indices;
  26615. vertexData.positions = positions;
  26616. vertexData.normals = normals;
  26617. vertexData.uvs = uvs;
  26618. return vertexData;
  26619. };
  26620. VertexData.CreateLines = function (points) {
  26621. var indices = [];
  26622. var positions = [];
  26623. for (var index = 0; index < points.length; index++) {
  26624. positions.push(points[index].x, points[index].y, points[index].z);
  26625. if (index > 0) {
  26626. indices.push(index - 1);
  26627. indices.push(index);
  26628. }
  26629. }
  26630. // Result
  26631. var vertexData = new VertexData();
  26632. vertexData.indices = indices;
  26633. vertexData.positions = positions;
  26634. return vertexData;
  26635. };
  26636. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26637. dashSize = dashSize || 3;
  26638. gapSize = gapSize || 1;
  26639. dashNb = dashNb || 200;
  26640. var positions = new Array();
  26641. var indices = new Array();
  26642. var curvect = BABYLON.Vector3.Zero();
  26643. var lg = 0;
  26644. var nb = 0;
  26645. var shft = 0;
  26646. var dashshft = 0;
  26647. var curshft = 0;
  26648. var idx = 0;
  26649. var i = 0;
  26650. for (i = 0; i < points.length - 1; i++) {
  26651. points[i + 1].subtractToRef(points[i], curvect);
  26652. lg += curvect.length();
  26653. }
  26654. shft = lg / dashNb;
  26655. dashshft = dashSize * shft / (dashSize + gapSize);
  26656. for (i = 0; i < points.length - 1; i++) {
  26657. points[i + 1].subtractToRef(points[i], curvect);
  26658. nb = Math.floor(curvect.length() / shft);
  26659. curvect.normalize();
  26660. for (var j = 0; j < nb; j++) {
  26661. curshft = shft * j;
  26662. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26663. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26664. indices.push(idx, idx + 1);
  26665. idx += 2;
  26666. }
  26667. }
  26668. // Result
  26669. var vertexData = new VertexData();
  26670. vertexData.positions = positions;
  26671. vertexData.indices = indices;
  26672. return vertexData;
  26673. };
  26674. VertexData.CreateGround = function (options, height, subdivisions) {
  26675. var indices = [];
  26676. var positions = [];
  26677. var normals = [];
  26678. var uvs = [];
  26679. var row, col;
  26680. var width;
  26681. if (options.width) {
  26682. width = options.width || 1;
  26683. height = options.height || 1;
  26684. subdivisions = options.subdivisions || 1;
  26685. }
  26686. else {
  26687. width = options || 1;
  26688. height = height || 1;
  26689. subdivisions = subdivisions || 1;
  26690. }
  26691. for (row = 0; row <= subdivisions; row++) {
  26692. for (col = 0; col <= subdivisions; col++) {
  26693. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26694. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26695. positions.push(position.x, position.y, position.z);
  26696. normals.push(normal.x, normal.y, normal.z);
  26697. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26698. }
  26699. }
  26700. for (row = 0; row < subdivisions; row++) {
  26701. for (col = 0; col < subdivisions; col++) {
  26702. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26703. indices.push(col + 1 + row * (subdivisions + 1));
  26704. indices.push(col + row * (subdivisions + 1));
  26705. indices.push(col + (row + 1) * (subdivisions + 1));
  26706. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26707. indices.push(col + row * (subdivisions + 1));
  26708. }
  26709. }
  26710. // Result
  26711. var vertexData = new VertexData();
  26712. vertexData.indices = indices;
  26713. vertexData.positions = positions;
  26714. vertexData.normals = normals;
  26715. vertexData.uvs = uvs;
  26716. return vertexData;
  26717. };
  26718. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26719. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26720. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26721. var indices = [];
  26722. var positions = [];
  26723. var normals = [];
  26724. var uvs = [];
  26725. var row, col, tileRow, tileCol;
  26726. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26727. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26728. precision.w = (precision.w < 1) ? 1 : precision.w;
  26729. precision.h = (precision.h < 1) ? 1 : precision.h;
  26730. var tileSize = {
  26731. 'w': (xmax - xmin) / subdivisions.w,
  26732. 'h': (zmax - zmin) / subdivisions.h
  26733. };
  26734. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26735. // Indices
  26736. var base = positions.length / 3;
  26737. var rowLength = precision.w + 1;
  26738. for (row = 0; row < precision.h; row++) {
  26739. for (col = 0; col < precision.w; col++) {
  26740. var square = [
  26741. base + col + row * rowLength,
  26742. base + (col + 1) + row * rowLength,
  26743. base + (col + 1) + (row + 1) * rowLength,
  26744. base + col + (row + 1) * rowLength
  26745. ];
  26746. indices.push(square[1]);
  26747. indices.push(square[2]);
  26748. indices.push(square[3]);
  26749. indices.push(square[0]);
  26750. indices.push(square[1]);
  26751. indices.push(square[3]);
  26752. }
  26753. }
  26754. // Position, normals and uvs
  26755. var position = BABYLON.Vector3.Zero();
  26756. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26757. for (row = 0; row <= precision.h; row++) {
  26758. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26759. for (col = 0; col <= precision.w; col++) {
  26760. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26761. position.y = 0;
  26762. positions.push(position.x, position.y, position.z);
  26763. normals.push(normal.x, normal.y, normal.z);
  26764. uvs.push(col / precision.w, row / precision.h);
  26765. }
  26766. }
  26767. }
  26768. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26769. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26770. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26771. }
  26772. }
  26773. // Result
  26774. var vertexData = new VertexData();
  26775. vertexData.indices = indices;
  26776. vertexData.positions = positions;
  26777. vertexData.normals = normals;
  26778. vertexData.uvs = uvs;
  26779. return vertexData;
  26780. };
  26781. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26782. var indices = [];
  26783. var positions = [];
  26784. var normals = [];
  26785. var uvs = [];
  26786. var row, col;
  26787. // Vertices
  26788. for (row = 0; row <= subdivisions; row++) {
  26789. for (col = 0; col <= subdivisions; col++) {
  26790. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26791. // Compute height
  26792. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26793. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26794. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26795. var r = buffer[pos] / 255.0;
  26796. var g = buffer[pos + 1] / 255.0;
  26797. var b = buffer[pos + 2] / 255.0;
  26798. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26799. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26800. // Add vertex
  26801. positions.push(position.x, position.y, position.z);
  26802. normals.push(0, 0, 0);
  26803. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26804. }
  26805. }
  26806. // Indices
  26807. for (row = 0; row < subdivisions; row++) {
  26808. for (col = 0; col < subdivisions; col++) {
  26809. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26810. indices.push(col + 1 + row * (subdivisions + 1));
  26811. indices.push(col + row * (subdivisions + 1));
  26812. indices.push(col + (row + 1) * (subdivisions + 1));
  26813. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26814. indices.push(col + row * (subdivisions + 1));
  26815. }
  26816. }
  26817. // Normals
  26818. VertexData.ComputeNormals(positions, indices, normals);
  26819. // Result
  26820. var vertexData = new VertexData();
  26821. vertexData.indices = indices;
  26822. vertexData.positions = positions;
  26823. vertexData.normals = normals;
  26824. vertexData.uvs = uvs;
  26825. return vertexData;
  26826. };
  26827. VertexData.CreatePlane = function (options, sideOrientation) {
  26828. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26829. var indices = [];
  26830. var positions = [];
  26831. var normals = [];
  26832. var uvs = [];
  26833. var width;
  26834. var height;
  26835. if (options.width) {
  26836. width = options.width || 1;
  26837. height = options.height || 1;
  26838. sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26839. }
  26840. else {
  26841. width = options || 1;
  26842. height = options || 1;
  26843. }
  26844. // Vertices
  26845. var halfWidth = width / 2.0;
  26846. var halfHeight = height / 2.0;
  26847. positions.push(-halfWidth, -halfHeight, 0);
  26848. normals.push(0, 0, -1.0);
  26849. uvs.push(0.0, 0.0);
  26850. positions.push(halfWidth, -halfHeight, 0);
  26851. normals.push(0, 0, -1.0);
  26852. uvs.push(1.0, 0.0);
  26853. positions.push(halfWidth, halfHeight, 0);
  26854. normals.push(0, 0, -1.0);
  26855. uvs.push(1.0, 1.0);
  26856. positions.push(-halfWidth, halfHeight, 0);
  26857. normals.push(0, 0, -1.0);
  26858. uvs.push(0.0, 1.0);
  26859. // Indices
  26860. indices.push(0);
  26861. indices.push(1);
  26862. indices.push(2);
  26863. indices.push(0);
  26864. indices.push(2);
  26865. indices.push(3);
  26866. // Sides
  26867. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26868. // Result
  26869. var vertexData = new VertexData();
  26870. vertexData.indices = indices;
  26871. vertexData.positions = positions;
  26872. vertexData.normals = normals;
  26873. vertexData.uvs = uvs;
  26874. return vertexData;
  26875. };
  26876. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26877. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26878. var positions = [];
  26879. var indices = [];
  26880. var normals = [];
  26881. var uvs = [];
  26882. // positions and uvs
  26883. positions.push(0, 0, 0); // disc center first
  26884. uvs.push(0.5, 0.5);
  26885. var step = Math.PI * 2 / tessellation;
  26886. for (var a = 0; a < Math.PI * 2; a += step) {
  26887. var x = Math.cos(a);
  26888. var y = Math.sin(a);
  26889. var u = (x + 1) / 2;
  26890. var v = (1 - y) / 2;
  26891. positions.push(radius * x, radius * y, 0);
  26892. uvs.push(u, v);
  26893. }
  26894. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26895. uvs.push(uvs[2], uvs[3]);
  26896. //indices
  26897. var vertexNb = positions.length / 3;
  26898. for (var i = 1; i < vertexNb - 1; i++) {
  26899. indices.push(i + 1, 0, i);
  26900. }
  26901. // result
  26902. VertexData.ComputeNormals(positions, indices, normals);
  26903. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26904. var vertexData = new VertexData();
  26905. vertexData.indices = indices;
  26906. vertexData.positions = positions;
  26907. vertexData.normals = normals;
  26908. vertexData.uvs = uvs;
  26909. return vertexData;
  26910. };
  26911. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26912. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26913. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26914. var indices = [];
  26915. var positions = [];
  26916. var normals = [];
  26917. var uvs = [];
  26918. radius = radius || 2;
  26919. tube = tube || 0.5;
  26920. radialSegments = radialSegments || 32;
  26921. tubularSegments = tubularSegments || 32;
  26922. p = p || 2;
  26923. q = q || 3;
  26924. // Helper
  26925. var getPos = function (angle) {
  26926. var cu = Math.cos(angle);
  26927. var su = Math.sin(angle);
  26928. var quOverP = q / p * angle;
  26929. var cs = Math.cos(quOverP);
  26930. var tx = radius * (2 + cs) * 0.5 * cu;
  26931. var ty = radius * (2 + cs) * su * 0.5;
  26932. var tz = radius * Math.sin(quOverP) * 0.5;
  26933. return new BABYLON.Vector3(tx, ty, tz);
  26934. };
  26935. // Vertices
  26936. var i;
  26937. var j;
  26938. for (i = 0; i <= radialSegments; i++) {
  26939. var modI = i % radialSegments;
  26940. var u = modI / radialSegments * 2 * p * Math.PI;
  26941. var p1 = getPos(u);
  26942. var p2 = getPos(u + 0.01);
  26943. var tang = p2.subtract(p1);
  26944. var n = p2.add(p1);
  26945. var bitan = BABYLON.Vector3.Cross(tang, n);
  26946. n = BABYLON.Vector3.Cross(bitan, tang);
  26947. bitan.normalize();
  26948. n.normalize();
  26949. for (j = 0; j < tubularSegments; j++) {
  26950. var modJ = j % tubularSegments;
  26951. var v = modJ / tubularSegments * 2 * Math.PI;
  26952. var cx = -tube * Math.cos(v);
  26953. var cy = tube * Math.sin(v);
  26954. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26955. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26956. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26957. uvs.push(i / radialSegments);
  26958. uvs.push(j / tubularSegments);
  26959. }
  26960. }
  26961. for (i = 0; i < radialSegments; i++) {
  26962. for (j = 0; j < tubularSegments; j++) {
  26963. var jNext = (j + 1) % tubularSegments;
  26964. var a = i * tubularSegments + j;
  26965. var b = (i + 1) * tubularSegments + j;
  26966. var c = (i + 1) * tubularSegments + jNext;
  26967. var d = i * tubularSegments + jNext;
  26968. indices.push(d);
  26969. indices.push(b);
  26970. indices.push(a);
  26971. indices.push(d);
  26972. indices.push(c);
  26973. indices.push(b);
  26974. }
  26975. }
  26976. // Normals
  26977. VertexData.ComputeNormals(positions, indices, normals);
  26978. // Sides
  26979. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26980. // Result
  26981. var vertexData = new VertexData();
  26982. vertexData.indices = indices;
  26983. vertexData.positions = positions;
  26984. vertexData.normals = normals;
  26985. vertexData.uvs = uvs;
  26986. return vertexData;
  26987. };
  26988. // Tools
  26989. /**
  26990. * @param {any} - positions (number[] or Float32Array)
  26991. * @param {any} - indices (number[] or Uint16Array)
  26992. * @param {any} - normals (number[] or Float32Array)
  26993. */
  26994. VertexData.ComputeNormals = function (positions, indices, normals) {
  26995. var index = 0;
  26996. // temp Vector3
  26997. var p1p2 = BABYLON.Vector3.Zero();
  26998. var p3p2 = BABYLON.Vector3.Zero();
  26999. var faceNormal = BABYLON.Vector3.Zero();
  27000. var vertexNormali1 = BABYLON.Vector3.Zero();
  27001. for (index = 0; index < positions.length; index++) {
  27002. normals[index] = 0.0;
  27003. }
  27004. // indice triplet = 1 face
  27005. var nbFaces = indices.length / 3;
  27006. for (index = 0; index < nbFaces; index++) {
  27007. var i1 = indices[index * 3];
  27008. var i2 = indices[index * 3 + 1];
  27009. var i3 = indices[index * 3 + 2];
  27010. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27011. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27012. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27013. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27014. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27015. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27016. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27017. faceNormal.normalize();
  27018. normals[i1 * 3] += faceNormal.x;
  27019. normals[i1 * 3 + 1] += faceNormal.y;
  27020. normals[i1 * 3 + 2] += faceNormal.z;
  27021. normals[i2 * 3] += faceNormal.x;
  27022. normals[i2 * 3 + 1] += faceNormal.y;
  27023. normals[i2 * 3 + 2] += faceNormal.z;
  27024. normals[i3 * 3] += faceNormal.x;
  27025. normals[i3 * 3 + 1] += faceNormal.y;
  27026. normals[i3 * 3 + 2] += faceNormal.z;
  27027. }
  27028. // last normalization
  27029. for (index = 0; index < normals.length / 3; index++) {
  27030. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27031. vertexNormali1.normalize();
  27032. normals[index * 3] = vertexNormali1.x;
  27033. normals[index * 3 + 1] = vertexNormali1.y;
  27034. normals[index * 3 + 2] = vertexNormali1.z;
  27035. }
  27036. };
  27037. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27038. var li = indices.length;
  27039. var ln = normals.length;
  27040. var i;
  27041. var n;
  27042. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27043. switch (sideOrientation) {
  27044. case BABYLON.Mesh.FRONTSIDE:
  27045. // nothing changed
  27046. break;
  27047. case BABYLON.Mesh.BACKSIDE:
  27048. var tmp;
  27049. // indices
  27050. for (i = 0; i < li; i += 3) {
  27051. tmp = indices[i];
  27052. indices[i] = indices[i + 2];
  27053. indices[i + 2] = tmp;
  27054. }
  27055. // normals
  27056. for (n = 0; n < ln; n++) {
  27057. normals[n] = -normals[n];
  27058. }
  27059. break;
  27060. case BABYLON.Mesh.DOUBLESIDE:
  27061. // positions
  27062. var lp = positions.length;
  27063. var l = lp / 3;
  27064. for (var p = 0; p < lp; p++) {
  27065. positions[lp + p] = positions[p];
  27066. }
  27067. // indices
  27068. for (i = 0; i < li; i += 3) {
  27069. indices[i + li] = indices[i + 2] + l;
  27070. indices[i + 1 + li] = indices[i + 1] + l;
  27071. indices[i + 2 + li] = indices[i] + l;
  27072. }
  27073. // normals
  27074. for (n = 0; n < ln; n++) {
  27075. normals[ln + n] = -normals[n];
  27076. }
  27077. // uvs
  27078. var lu = uvs.length;
  27079. for (var u = 0; u < lu; u++) {
  27080. uvs[u + lu] = uvs[u];
  27081. }
  27082. break;
  27083. }
  27084. };
  27085. return VertexData;
  27086. })();
  27087. BABYLON.VertexData = VertexData;
  27088. })(BABYLON || (BABYLON = {}));
  27089. var BABYLON;
  27090. (function (BABYLON) {
  27091. var AnaglyphPostProcess = (function (_super) {
  27092. __extends(AnaglyphPostProcess, _super);
  27093. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27094. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27095. }
  27096. return AnaglyphPostProcess;
  27097. })(BABYLON.PostProcess);
  27098. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27099. })(BABYLON || (BABYLON = {}));
  27100. var BABYLON;
  27101. (function (BABYLON) {
  27102. var Tags = (function () {
  27103. function Tags() {
  27104. }
  27105. Tags.EnableFor = function (obj) {
  27106. obj._tags = obj._tags || {};
  27107. obj.hasTags = function () {
  27108. return Tags.HasTags(obj);
  27109. };
  27110. obj.addTags = function (tagsString) {
  27111. return Tags.AddTagsTo(obj, tagsString);
  27112. };
  27113. obj.removeTags = function (tagsString) {
  27114. return Tags.RemoveTagsFrom(obj, tagsString);
  27115. };
  27116. obj.matchesTagsQuery = function (tagsQuery) {
  27117. return Tags.MatchesQuery(obj, tagsQuery);
  27118. };
  27119. };
  27120. Tags.DisableFor = function (obj) {
  27121. delete obj._tags;
  27122. delete obj.hasTags;
  27123. delete obj.addTags;
  27124. delete obj.removeTags;
  27125. delete obj.matchesTagsQuery;
  27126. };
  27127. Tags.HasTags = function (obj) {
  27128. if (!obj._tags) {
  27129. return false;
  27130. }
  27131. return !BABYLON.Tools.IsEmpty(obj._tags);
  27132. };
  27133. Tags.GetTags = function (obj) {
  27134. if (!obj._tags) {
  27135. return null;
  27136. }
  27137. return obj._tags;
  27138. };
  27139. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27140. // a tag cannot start with '||', '&&', and '!'
  27141. // it cannot contain whitespaces
  27142. Tags.AddTagsTo = function (obj, tagsString) {
  27143. if (!tagsString) {
  27144. return;
  27145. }
  27146. var tags = tagsString.split(" ");
  27147. for (var t in tags) {
  27148. Tags._AddTagTo(obj, tags[t]);
  27149. }
  27150. };
  27151. Tags._AddTagTo = function (obj, tag) {
  27152. tag = tag.trim();
  27153. if (tag === "" || tag === "true" || tag === "false") {
  27154. return;
  27155. }
  27156. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27157. return;
  27158. }
  27159. Tags.EnableFor(obj);
  27160. obj._tags[tag] = true;
  27161. };
  27162. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27163. if (!Tags.HasTags(obj)) {
  27164. return;
  27165. }
  27166. var tags = tagsString.split(" ");
  27167. for (var t in tags) {
  27168. Tags._RemoveTagFrom(obj, tags[t]);
  27169. }
  27170. };
  27171. Tags._RemoveTagFrom = function (obj, tag) {
  27172. delete obj._tags[tag];
  27173. };
  27174. Tags.MatchesQuery = function (obj, tagsQuery) {
  27175. if (tagsQuery === undefined) {
  27176. return true;
  27177. }
  27178. if (tagsQuery === "") {
  27179. return Tags.HasTags(obj);
  27180. }
  27181. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27182. };
  27183. return Tags;
  27184. })();
  27185. BABYLON.Tags = Tags;
  27186. })(BABYLON || (BABYLON = {}));
  27187. var BABYLON;
  27188. (function (BABYLON) {
  27189. var Internals;
  27190. (function (Internals) {
  27191. var AndOrNotEvaluator = (function () {
  27192. function AndOrNotEvaluator() {
  27193. }
  27194. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27195. if (!query.match(/\([^\(\)]*\)/g)) {
  27196. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27197. }
  27198. else {
  27199. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27200. // remove parenthesis
  27201. r = r.slice(1, r.length - 1);
  27202. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27203. });
  27204. }
  27205. if (query === "true") {
  27206. return true;
  27207. }
  27208. if (query === "false") {
  27209. return false;
  27210. }
  27211. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27212. };
  27213. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27214. evaluateCallback = evaluateCallback || (function (r) {
  27215. return r === "true" ? true : false;
  27216. });
  27217. var result;
  27218. var or = parenthesisContent.split("||");
  27219. for (var i in or) {
  27220. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27221. var and = ori.split("&&");
  27222. if (and.length > 1) {
  27223. for (var j = 0; j < and.length; ++j) {
  27224. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27225. if (andj !== "true" && andj !== "false") {
  27226. if (andj[0] === "!") {
  27227. result = !evaluateCallback(andj.substring(1));
  27228. }
  27229. else {
  27230. result = evaluateCallback(andj);
  27231. }
  27232. }
  27233. else {
  27234. result = andj === "true" ? true : false;
  27235. }
  27236. if (!result) {
  27237. ori = "false";
  27238. break;
  27239. }
  27240. }
  27241. }
  27242. if (result || ori === "true") {
  27243. result = true;
  27244. break;
  27245. }
  27246. // result equals false (or undefined)
  27247. if (ori !== "true" && ori !== "false") {
  27248. if (ori[0] === "!") {
  27249. result = !evaluateCallback(ori.substring(1));
  27250. }
  27251. else {
  27252. result = evaluateCallback(ori);
  27253. }
  27254. }
  27255. else {
  27256. result = ori === "true" ? true : false;
  27257. }
  27258. }
  27259. // the whole parenthesis scope is replaced by 'true' or 'false'
  27260. return result ? "true" : "false";
  27261. };
  27262. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27263. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27264. // remove whitespaces
  27265. r = r.replace(/[\s]/g, function () { return ""; });
  27266. return r.length % 2 ? "!" : "";
  27267. });
  27268. booleanString = booleanString.trim();
  27269. if (booleanString === "!true") {
  27270. booleanString = "false";
  27271. }
  27272. else if (booleanString === "!false") {
  27273. booleanString = "true";
  27274. }
  27275. return booleanString;
  27276. };
  27277. return AndOrNotEvaluator;
  27278. })();
  27279. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27280. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27281. })(BABYLON || (BABYLON = {}));
  27282. var BABYLON;
  27283. (function (BABYLON) {
  27284. var PostProcessRenderPass = (function () {
  27285. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27286. this._enabled = true;
  27287. this._refCount = 0;
  27288. this._name = name;
  27289. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27290. this.setRenderList(renderList);
  27291. this._renderTexture.onBeforeRender = beforeRender;
  27292. this._renderTexture.onAfterRender = afterRender;
  27293. this._scene = scene;
  27294. this._renderList = renderList;
  27295. }
  27296. // private
  27297. PostProcessRenderPass.prototype._incRefCount = function () {
  27298. if (this._refCount === 0) {
  27299. this._scene.customRenderTargets.push(this._renderTexture);
  27300. }
  27301. return ++this._refCount;
  27302. };
  27303. PostProcessRenderPass.prototype._decRefCount = function () {
  27304. this._refCount--;
  27305. if (this._refCount <= 0) {
  27306. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27307. }
  27308. return this._refCount;
  27309. };
  27310. PostProcessRenderPass.prototype._update = function () {
  27311. this.setRenderList(this._renderList);
  27312. };
  27313. // public
  27314. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27315. this._renderTexture.renderList = renderList;
  27316. };
  27317. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27318. return this._renderTexture;
  27319. };
  27320. return PostProcessRenderPass;
  27321. })();
  27322. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27323. })(BABYLON || (BABYLON = {}));
  27324. var BABYLON;
  27325. (function (BABYLON) {
  27326. var PostProcessRenderEffect = (function () {
  27327. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27328. this._engine = engine;
  27329. this._name = name;
  27330. this._singleInstance = singleInstance || true;
  27331. this._getPostProcess = getPostProcess;
  27332. this._cameras = [];
  27333. this._indicesForCamera = [];
  27334. this._postProcesses = {};
  27335. this._renderPasses = {};
  27336. this._renderEffectAsPasses = {};
  27337. }
  27338. PostProcessRenderEffect.prototype._update = function () {
  27339. for (var renderPassName in this._renderPasses) {
  27340. this._renderPasses[renderPassName]._update();
  27341. }
  27342. };
  27343. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27344. this._renderPasses[renderPass._name] = renderPass;
  27345. this._linkParameters();
  27346. };
  27347. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27348. delete this._renderPasses[renderPass._name];
  27349. this._linkParameters();
  27350. };
  27351. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27352. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27353. this._linkParameters();
  27354. };
  27355. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27356. for (var renderPassName in this._renderPasses) {
  27357. if (renderPassName === passName) {
  27358. return this._renderPasses[passName];
  27359. }
  27360. }
  27361. };
  27362. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27363. this._renderPasses = {};
  27364. this._linkParameters();
  27365. };
  27366. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27367. var cameraKey;
  27368. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27369. for (var i = 0; i < _cam.length; i++) {
  27370. var camera = _cam[i];
  27371. var cameraName = camera.name;
  27372. if (this._singleInstance) {
  27373. cameraKey = 0;
  27374. }
  27375. else {
  27376. cameraKey = cameraName;
  27377. }
  27378. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27379. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27380. if (!this._indicesForCamera[cameraName]) {
  27381. this._indicesForCamera[cameraName] = [];
  27382. }
  27383. this._indicesForCamera[cameraName].push(index);
  27384. if (this._cameras.indexOf(camera) === -1) {
  27385. this._cameras[cameraName] = camera;
  27386. }
  27387. for (var passName in this._renderPasses) {
  27388. this._renderPasses[passName]._incRefCount();
  27389. }
  27390. }
  27391. this._linkParameters();
  27392. };
  27393. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27394. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27395. for (var i = 0; i < _cam.length; i++) {
  27396. var camera = _cam[i];
  27397. var cameraName = camera.name;
  27398. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27399. var index = this._cameras.indexOf(cameraName);
  27400. this._indicesForCamera.splice(index, 1);
  27401. this._cameras.splice(index, 1);
  27402. for (var passName in this._renderPasses) {
  27403. this._renderPasses[passName]._decRefCount();
  27404. }
  27405. }
  27406. };
  27407. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27408. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27409. for (var i = 0; i < _cam.length; i++) {
  27410. var camera = _cam[i];
  27411. var cameraName = camera.name;
  27412. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27413. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27414. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27415. }
  27416. }
  27417. for (var passName in this._renderPasses) {
  27418. this._renderPasses[passName]._incRefCount();
  27419. }
  27420. }
  27421. };
  27422. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27423. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27424. for (var i = 0; i < _cam.length; i++) {
  27425. var camera = _cam[i];
  27426. var cameraName = camera.Name;
  27427. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27428. for (var passName in this._renderPasses) {
  27429. this._renderPasses[passName]._decRefCount();
  27430. }
  27431. }
  27432. };
  27433. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27434. if (this._singleInstance) {
  27435. return this._postProcesses[0];
  27436. }
  27437. else {
  27438. return this._postProcesses[camera.name];
  27439. }
  27440. };
  27441. PostProcessRenderEffect.prototype._linkParameters = function () {
  27442. var _this = this;
  27443. for (var index in this._postProcesses) {
  27444. if (this.applyParameters) {
  27445. this.applyParameters(this._postProcesses[index]);
  27446. }
  27447. this._postProcesses[index].onBeforeRender = function (effect) {
  27448. _this._linkTextures(effect);
  27449. };
  27450. }
  27451. };
  27452. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27453. for (var renderPassName in this._renderPasses) {
  27454. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27455. }
  27456. for (var renderEffectName in this._renderEffectAsPasses) {
  27457. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27458. }
  27459. };
  27460. return PostProcessRenderEffect;
  27461. })();
  27462. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27463. })(BABYLON || (BABYLON = {}));
  27464. var BABYLON;
  27465. (function (BABYLON) {
  27466. var PostProcessRenderPipeline = (function () {
  27467. function PostProcessRenderPipeline(engine, name) {
  27468. this._engine = engine;
  27469. this._name = name;
  27470. this._renderEffects = {};
  27471. this._renderEffectsForIsolatedPass = {};
  27472. this._cameras = [];
  27473. }
  27474. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27475. this._renderEffects[renderEffect._name] = renderEffect;
  27476. };
  27477. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27478. var renderEffects = this._renderEffects[renderEffectName];
  27479. if (!renderEffects) {
  27480. return;
  27481. }
  27482. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27483. };
  27484. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27485. var renderEffects = this._renderEffects[renderEffectName];
  27486. if (!renderEffects) {
  27487. return;
  27488. }
  27489. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27490. };
  27491. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27492. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27493. var indicesToDelete = [];
  27494. for (var i = 0; i < _cam.length; i++) {
  27495. var camera = _cam[i];
  27496. var cameraName = camera.name;
  27497. if (this._cameras.indexOf(camera) === -1) {
  27498. this._cameras[cameraName] = camera;
  27499. }
  27500. else if (unique) {
  27501. indicesToDelete.push(i);
  27502. }
  27503. }
  27504. for (var i = 0; i < indicesToDelete.length; i++) {
  27505. cameras.splice(indicesToDelete[i], 1);
  27506. }
  27507. for (var renderEffectName in this._renderEffects) {
  27508. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27509. }
  27510. };
  27511. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27512. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27513. for (var renderEffectName in this._renderEffects) {
  27514. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27515. }
  27516. for (var i = 0; i < _cam.length; i++) {
  27517. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27518. }
  27519. };
  27520. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27521. var _this = this;
  27522. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27523. var pass = null;
  27524. for (var renderEffectName in this._renderEffects) {
  27525. pass = this._renderEffects[renderEffectName].getPass(passName);
  27526. if (pass != null) {
  27527. break;
  27528. }
  27529. }
  27530. if (pass === null) {
  27531. return;
  27532. }
  27533. for (var renderEffectName in this._renderEffects) {
  27534. this._renderEffects[renderEffectName]._disable(_cam);
  27535. }
  27536. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27537. for (var i = 0; i < _cam.length; i++) {
  27538. var camera = _cam[i];
  27539. var cameraName = camera.name;
  27540. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  27541. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27542. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27543. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27544. }
  27545. };
  27546. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27547. var _this = this;
  27548. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27549. for (var i = 0; i < _cam.length; i++) {
  27550. var camera = _cam[i];
  27551. var cameraName = camera.name;
  27552. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  27553. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27554. }
  27555. for (var renderEffectName in this._renderEffects) {
  27556. this._renderEffects[renderEffectName]._enable(_cam);
  27557. }
  27558. };
  27559. PostProcessRenderPipeline.prototype._update = function () {
  27560. for (var renderEffectName in this._renderEffects) {
  27561. this._renderEffects[renderEffectName]._update();
  27562. }
  27563. for (var i = 0; i < this._cameras.length; i++) {
  27564. var cameraName = this._cameras[i].name;
  27565. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27566. this._renderEffectsForIsolatedPass[cameraName]._update();
  27567. }
  27568. }
  27569. };
  27570. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27571. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27572. return PostProcessRenderPipeline;
  27573. })();
  27574. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27575. })(BABYLON || (BABYLON = {}));
  27576. var BABYLON;
  27577. (function (BABYLON) {
  27578. var PostProcessRenderPipelineManager = (function () {
  27579. function PostProcessRenderPipelineManager() {
  27580. this._renderPipelines = {};
  27581. }
  27582. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27583. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27584. };
  27585. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27586. var renderPipeline = this._renderPipelines[renderPipelineName];
  27587. if (!renderPipeline) {
  27588. return;
  27589. }
  27590. renderPipeline._attachCameras(cameras, unique);
  27591. };
  27592. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27593. var renderPipeline = this._renderPipelines[renderPipelineName];
  27594. if (!renderPipeline) {
  27595. return;
  27596. }
  27597. renderPipeline._detachCameras(cameras);
  27598. };
  27599. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27600. var renderPipeline = this._renderPipelines[renderPipelineName];
  27601. if (!renderPipeline) {
  27602. return;
  27603. }
  27604. renderPipeline._enableEffect(renderEffectName, cameras);
  27605. };
  27606. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27607. var renderPipeline = this._renderPipelines[renderPipelineName];
  27608. if (!renderPipeline) {
  27609. return;
  27610. }
  27611. renderPipeline._disableEffect(renderEffectName, cameras);
  27612. };
  27613. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27614. var renderPipeline = this._renderPipelines[renderPipelineName];
  27615. if (!renderPipeline) {
  27616. return;
  27617. }
  27618. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27619. };
  27620. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27621. var renderPipeline = this._renderPipelines[renderPipelineName];
  27622. if (!renderPipeline) {
  27623. return;
  27624. }
  27625. renderPipeline._disableDisplayOnlyPass(cameras);
  27626. };
  27627. PostProcessRenderPipelineManager.prototype.update = function () {
  27628. for (var renderPipelineName in this._renderPipelines) {
  27629. this._renderPipelines[renderPipelineName]._update();
  27630. }
  27631. };
  27632. return PostProcessRenderPipelineManager;
  27633. })();
  27634. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27635. })(BABYLON || (BABYLON = {}));
  27636. var BABYLON;
  27637. (function (BABYLON) {
  27638. var DisplayPassPostProcess = (function (_super) {
  27639. __extends(DisplayPassPostProcess, _super);
  27640. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27641. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27642. }
  27643. return DisplayPassPostProcess;
  27644. })(BABYLON.PostProcess);
  27645. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27646. })(BABYLON || (BABYLON = {}));
  27647. var BABYLON;
  27648. (function (BABYLON) {
  27649. var BoundingBoxRenderer = (function () {
  27650. function BoundingBoxRenderer(scene) {
  27651. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27652. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27653. this.showBackLines = true;
  27654. this.renderList = new BABYLON.SmartArray(32);
  27655. this._scene = scene;
  27656. }
  27657. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27658. if (this._colorShader) {
  27659. return;
  27660. }
  27661. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27662. attributes: ["position"],
  27663. uniforms: ["worldViewProjection", "color"]
  27664. });
  27665. var engine = this._scene.getEngine();
  27666. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27667. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27668. 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]);
  27669. };
  27670. BoundingBoxRenderer.prototype.reset = function () {
  27671. this.renderList.reset();
  27672. };
  27673. BoundingBoxRenderer.prototype.render = function () {
  27674. if (this.renderList.length === 0) {
  27675. return;
  27676. }
  27677. this._prepareRessources();
  27678. if (!this._colorShader.isReady()) {
  27679. return;
  27680. }
  27681. var engine = this._scene.getEngine();
  27682. engine.setDepthWrite(false);
  27683. this._colorShader._preBind();
  27684. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27685. var boundingBox = this.renderList.data[boundingBoxIndex];
  27686. var min = boundingBox.minimum;
  27687. var max = boundingBox.maximum;
  27688. var diff = max.subtract(min);
  27689. var median = min.add(diff.scale(0.5));
  27690. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27691. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27692. .multiply(boundingBox.getWorldMatrix());
  27693. // VBOs
  27694. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27695. if (this.showBackLines) {
  27696. // Back
  27697. engine.setDepthFunctionToGreaterOrEqual();
  27698. this._scene.resetCachedMaterial();
  27699. this._colorShader.setColor4("color", this.backColor.toColor4());
  27700. this._colorShader.bind(worldMatrix);
  27701. // Draw order
  27702. engine.draw(false, 0, 24);
  27703. }
  27704. // Front
  27705. engine.setDepthFunctionToLess();
  27706. this._scene.resetCachedMaterial();
  27707. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27708. this._colorShader.bind(worldMatrix);
  27709. // Draw order
  27710. engine.draw(false, 0, 24);
  27711. }
  27712. this._colorShader.unbind();
  27713. engine.setDepthFunctionToLessOrEqual();
  27714. engine.setDepthWrite(true);
  27715. };
  27716. BoundingBoxRenderer.prototype.dispose = function () {
  27717. if (!this._colorShader) {
  27718. return;
  27719. }
  27720. this._colorShader.dispose();
  27721. this._vb.dispose();
  27722. this._scene.getEngine()._releaseBuffer(this._ib);
  27723. };
  27724. return BoundingBoxRenderer;
  27725. })();
  27726. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27727. })(BABYLON || (BABYLON = {}));
  27728. var BABYLON;
  27729. (function (BABYLON) {
  27730. var Condition = (function () {
  27731. function Condition(actionManager) {
  27732. this._actionManager = actionManager;
  27733. }
  27734. Condition.prototype.isValid = function () {
  27735. return true;
  27736. };
  27737. Condition.prototype._getProperty = function (propertyPath) {
  27738. return this._actionManager._getProperty(propertyPath);
  27739. };
  27740. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27741. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27742. };
  27743. return Condition;
  27744. })();
  27745. BABYLON.Condition = Condition;
  27746. var ValueCondition = (function (_super) {
  27747. __extends(ValueCondition, _super);
  27748. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27749. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27750. _super.call(this, actionManager);
  27751. this.propertyPath = propertyPath;
  27752. this.value = value;
  27753. this.operator = operator;
  27754. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27755. this._property = this._getProperty(this.propertyPath);
  27756. }
  27757. Object.defineProperty(ValueCondition, "IsEqual", {
  27758. get: function () {
  27759. return ValueCondition._IsEqual;
  27760. },
  27761. enumerable: true,
  27762. configurable: true
  27763. });
  27764. Object.defineProperty(ValueCondition, "IsDifferent", {
  27765. get: function () {
  27766. return ValueCondition._IsDifferent;
  27767. },
  27768. enumerable: true,
  27769. configurable: true
  27770. });
  27771. Object.defineProperty(ValueCondition, "IsGreater", {
  27772. get: function () {
  27773. return ValueCondition._IsGreater;
  27774. },
  27775. enumerable: true,
  27776. configurable: true
  27777. });
  27778. Object.defineProperty(ValueCondition, "IsLesser", {
  27779. get: function () {
  27780. return ValueCondition._IsLesser;
  27781. },
  27782. enumerable: true,
  27783. configurable: true
  27784. });
  27785. // Methods
  27786. ValueCondition.prototype.isValid = function () {
  27787. switch (this.operator) {
  27788. case ValueCondition.IsGreater:
  27789. return this._target[this._property] > this.value;
  27790. case ValueCondition.IsLesser:
  27791. return this._target[this._property] < this.value;
  27792. case ValueCondition.IsEqual:
  27793. case ValueCondition.IsDifferent:
  27794. var check;
  27795. if (this.value.equals) {
  27796. check = this.value.equals(this._target[this._property]);
  27797. }
  27798. else {
  27799. check = this.value === this._target[this._property];
  27800. }
  27801. return this.operator === ValueCondition.IsEqual ? check : !check;
  27802. }
  27803. return false;
  27804. };
  27805. // Statics
  27806. ValueCondition._IsEqual = 0;
  27807. ValueCondition._IsDifferent = 1;
  27808. ValueCondition._IsGreater = 2;
  27809. ValueCondition._IsLesser = 3;
  27810. return ValueCondition;
  27811. })(Condition);
  27812. BABYLON.ValueCondition = ValueCondition;
  27813. var PredicateCondition = (function (_super) {
  27814. __extends(PredicateCondition, _super);
  27815. function PredicateCondition(actionManager, predicate) {
  27816. _super.call(this, actionManager);
  27817. this.predicate = predicate;
  27818. }
  27819. PredicateCondition.prototype.isValid = function () {
  27820. return this.predicate();
  27821. };
  27822. return PredicateCondition;
  27823. })(Condition);
  27824. BABYLON.PredicateCondition = PredicateCondition;
  27825. var StateCondition = (function (_super) {
  27826. __extends(StateCondition, _super);
  27827. function StateCondition(actionManager, target, value) {
  27828. _super.call(this, actionManager);
  27829. this.value = value;
  27830. this._target = target;
  27831. }
  27832. // Methods
  27833. StateCondition.prototype.isValid = function () {
  27834. return this._target.state === this.value;
  27835. };
  27836. return StateCondition;
  27837. })(Condition);
  27838. BABYLON.StateCondition = StateCondition;
  27839. })(BABYLON || (BABYLON = {}));
  27840. var BABYLON;
  27841. (function (BABYLON) {
  27842. var Action = (function () {
  27843. function Action(triggerOptions, condition) {
  27844. this.triggerOptions = triggerOptions;
  27845. if (triggerOptions.parameter) {
  27846. this.trigger = triggerOptions.trigger;
  27847. this._triggerParameter = triggerOptions.parameter;
  27848. }
  27849. else {
  27850. this.trigger = triggerOptions;
  27851. }
  27852. this._nextActiveAction = this;
  27853. this._condition = condition;
  27854. }
  27855. // Methods
  27856. Action.prototype._prepare = function () {
  27857. };
  27858. Action.prototype.getTriggerParameter = function () {
  27859. return this._triggerParameter;
  27860. };
  27861. Action.prototype._executeCurrent = function (evt) {
  27862. if (this._nextActiveAction._condition) {
  27863. var condition = this._nextActiveAction._condition;
  27864. var currentRenderId = this._actionManager.getScene().getRenderId();
  27865. // We cache the current evaluation for the current frame
  27866. if (condition._evaluationId === currentRenderId) {
  27867. if (!condition._currentResult) {
  27868. return;
  27869. }
  27870. }
  27871. else {
  27872. condition._evaluationId = currentRenderId;
  27873. if (!condition.isValid()) {
  27874. condition._currentResult = false;
  27875. return;
  27876. }
  27877. condition._currentResult = true;
  27878. }
  27879. }
  27880. this._nextActiveAction.execute(evt);
  27881. if (this._nextActiveAction._child) {
  27882. if (!this._nextActiveAction._child._actionManager) {
  27883. this._nextActiveAction._child._actionManager = this._actionManager;
  27884. }
  27885. this._nextActiveAction = this._nextActiveAction._child;
  27886. }
  27887. else {
  27888. this._nextActiveAction = this;
  27889. }
  27890. };
  27891. Action.prototype.execute = function (evt) {
  27892. };
  27893. Action.prototype.then = function (action) {
  27894. this._child = action;
  27895. action._actionManager = this._actionManager;
  27896. action._prepare();
  27897. return action;
  27898. };
  27899. Action.prototype._getProperty = function (propertyPath) {
  27900. return this._actionManager._getProperty(propertyPath);
  27901. };
  27902. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27903. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27904. };
  27905. return Action;
  27906. })();
  27907. BABYLON.Action = Action;
  27908. })(BABYLON || (BABYLON = {}));
  27909. var BABYLON;
  27910. (function (BABYLON) {
  27911. /**
  27912. * ActionEvent is the event beint sent when an action is triggered.
  27913. */
  27914. var ActionEvent = (function () {
  27915. /**
  27916. * @constructor
  27917. * @param source The mesh that triggered the action.
  27918. * @param pointerX the X mouse cursor position at the time of the event
  27919. * @param pointerY the Y mouse cursor position at the time of the event
  27920. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27921. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27922. */
  27923. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27924. this.source = source;
  27925. this.pointerX = pointerX;
  27926. this.pointerY = pointerY;
  27927. this.meshUnderPointer = meshUnderPointer;
  27928. this.sourceEvent = sourceEvent;
  27929. this.additionalData = additionalData;
  27930. }
  27931. /**
  27932. * Helper function to auto-create an ActionEvent from a source mesh.
  27933. * @param source the source mesh that triggered the event
  27934. * @param evt {Event} The original (browser) event
  27935. */
  27936. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27937. var scene = source.getScene();
  27938. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27939. };
  27940. /**
  27941. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27942. * @param scene the scene where the event occurred
  27943. * @param evt {Event} The original (browser) event
  27944. */
  27945. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27946. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27947. };
  27948. return ActionEvent;
  27949. })();
  27950. BABYLON.ActionEvent = ActionEvent;
  27951. /**
  27952. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27953. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27954. */
  27955. var ActionManager = (function () {
  27956. function ActionManager(scene) {
  27957. // Members
  27958. this.actions = new Array();
  27959. this._scene = scene;
  27960. scene._actionManagers.push(this);
  27961. }
  27962. Object.defineProperty(ActionManager, "NothingTrigger", {
  27963. get: function () {
  27964. return ActionManager._NothingTrigger;
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27970. get: function () {
  27971. return ActionManager._OnPickTrigger;
  27972. },
  27973. enumerable: true,
  27974. configurable: true
  27975. });
  27976. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27977. get: function () {
  27978. return ActionManager._OnLeftPickTrigger;
  27979. },
  27980. enumerable: true,
  27981. configurable: true
  27982. });
  27983. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27984. get: function () {
  27985. return ActionManager._OnRightPickTrigger;
  27986. },
  27987. enumerable: true,
  27988. configurable: true
  27989. });
  27990. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27991. get: function () {
  27992. return ActionManager._OnCenterPickTrigger;
  27993. },
  27994. enumerable: true,
  27995. configurable: true
  27996. });
  27997. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27998. get: function () {
  27999. return ActionManager._OnPointerOverTrigger;
  28000. },
  28001. enumerable: true,
  28002. configurable: true
  28003. });
  28004. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28005. get: function () {
  28006. return ActionManager._OnPointerOutTrigger;
  28007. },
  28008. enumerable: true,
  28009. configurable: true
  28010. });
  28011. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28012. get: function () {
  28013. return ActionManager._OnEveryFrameTrigger;
  28014. },
  28015. enumerable: true,
  28016. configurable: true
  28017. });
  28018. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28019. get: function () {
  28020. return ActionManager._OnIntersectionEnterTrigger;
  28021. },
  28022. enumerable: true,
  28023. configurable: true
  28024. });
  28025. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28026. get: function () {
  28027. return ActionManager._OnIntersectionExitTrigger;
  28028. },
  28029. enumerable: true,
  28030. configurable: true
  28031. });
  28032. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28033. get: function () {
  28034. return ActionManager._OnKeyDownTrigger;
  28035. },
  28036. enumerable: true,
  28037. configurable: true
  28038. });
  28039. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28040. get: function () {
  28041. return ActionManager._OnKeyUpTrigger;
  28042. },
  28043. enumerable: true,
  28044. configurable: true
  28045. });
  28046. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28047. get: function () {
  28048. return ActionManager._OnPickUpTrigger;
  28049. },
  28050. enumerable: true,
  28051. configurable: true
  28052. });
  28053. // Methods
  28054. ActionManager.prototype.dispose = function () {
  28055. var index = this._scene._actionManagers.indexOf(this);
  28056. if (index > -1) {
  28057. this._scene._actionManagers.splice(index, 1);
  28058. }
  28059. };
  28060. ActionManager.prototype.getScene = function () {
  28061. return this._scene;
  28062. };
  28063. /**
  28064. * Does this action manager handles actions of any of the given triggers
  28065. * @param {number[]} triggers - the triggers to be tested
  28066. * @return {boolean} whether one (or more) of the triggers is handeled
  28067. */
  28068. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28069. for (var index = 0; index < this.actions.length; index++) {
  28070. var action = this.actions[index];
  28071. if (triggers.indexOf(action.trigger) > -1) {
  28072. return true;
  28073. }
  28074. }
  28075. return false;
  28076. };
  28077. /**
  28078. * Does this action manager handles actions of a given trigger
  28079. * @param {number} trigger - the trigger to be tested
  28080. * @return {boolean} whether the trigger is handeled
  28081. */
  28082. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28083. for (var index = 0; index < this.actions.length; index++) {
  28084. var action = this.actions[index];
  28085. if (action.trigger === trigger) {
  28086. return true;
  28087. }
  28088. }
  28089. return false;
  28090. };
  28091. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28092. /**
  28093. * Does this action manager has pointer triggers
  28094. * @return {boolean} whether or not it has pointer triggers
  28095. */
  28096. get: function () {
  28097. for (var index = 0; index < this.actions.length; index++) {
  28098. var action = this.actions[index];
  28099. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28100. return true;
  28101. }
  28102. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28103. return true;
  28104. }
  28105. }
  28106. return false;
  28107. },
  28108. enumerable: true,
  28109. configurable: true
  28110. });
  28111. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28112. /**
  28113. * Does this action manager has pick triggers
  28114. * @return {boolean} whether or not it has pick triggers
  28115. */
  28116. get: function () {
  28117. for (var index = 0; index < this.actions.length; index++) {
  28118. var action = this.actions[index];
  28119. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28120. return true;
  28121. }
  28122. }
  28123. return false;
  28124. },
  28125. enumerable: true,
  28126. configurable: true
  28127. });
  28128. /**
  28129. * Registers an action to this action manager
  28130. * @param {BABYLON.Action} action - the action to be registered
  28131. * @return {BABYLON.Action} the action amended (prepared) after registration
  28132. */
  28133. ActionManager.prototype.registerAction = function (action) {
  28134. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28135. if (this.getScene().actionManager !== this) {
  28136. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28137. return null;
  28138. }
  28139. }
  28140. this.actions.push(action);
  28141. action._actionManager = this;
  28142. action._prepare();
  28143. return action;
  28144. };
  28145. /**
  28146. * Process a specific trigger
  28147. * @param {number} trigger - the trigger to process
  28148. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28149. */
  28150. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28151. for (var index = 0; index < this.actions.length; index++) {
  28152. var action = this.actions[index];
  28153. if (action.trigger === trigger) {
  28154. if (trigger === ActionManager.OnKeyUpTrigger
  28155. || trigger === ActionManager.OnKeyDownTrigger) {
  28156. var parameter = action.getTriggerParameter();
  28157. if (parameter) {
  28158. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28159. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28160. if (actualkey !== parameter.toLowerCase()) {
  28161. continue;
  28162. }
  28163. }
  28164. }
  28165. action._executeCurrent(evt);
  28166. }
  28167. }
  28168. };
  28169. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28170. var properties = propertyPath.split(".");
  28171. for (var index = 0; index < properties.length - 1; index++) {
  28172. target = target[properties[index]];
  28173. }
  28174. return target;
  28175. };
  28176. ActionManager.prototype._getProperty = function (propertyPath) {
  28177. var properties = propertyPath.split(".");
  28178. return properties[properties.length - 1];
  28179. };
  28180. // Statics
  28181. ActionManager._NothingTrigger = 0;
  28182. ActionManager._OnPickTrigger = 1;
  28183. ActionManager._OnLeftPickTrigger = 2;
  28184. ActionManager._OnRightPickTrigger = 3;
  28185. ActionManager._OnCenterPickTrigger = 4;
  28186. ActionManager._OnPointerOverTrigger = 5;
  28187. ActionManager._OnPointerOutTrigger = 6;
  28188. ActionManager._OnEveryFrameTrigger = 7;
  28189. ActionManager._OnIntersectionEnterTrigger = 8;
  28190. ActionManager._OnIntersectionExitTrigger = 9;
  28191. ActionManager._OnKeyDownTrigger = 10;
  28192. ActionManager._OnKeyUpTrigger = 11;
  28193. ActionManager._OnPickUpTrigger = 12;
  28194. return ActionManager;
  28195. })();
  28196. BABYLON.ActionManager = ActionManager;
  28197. })(BABYLON || (BABYLON = {}));
  28198. var BABYLON;
  28199. (function (BABYLON) {
  28200. var InterpolateValueAction = (function (_super) {
  28201. __extends(InterpolateValueAction, _super);
  28202. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28203. if (duration === void 0) { duration = 1000; }
  28204. _super.call(this, triggerOptions, condition);
  28205. this.propertyPath = propertyPath;
  28206. this.value = value;
  28207. this.duration = duration;
  28208. this.stopOtherAnimations = stopOtherAnimations;
  28209. this._target = target;
  28210. }
  28211. InterpolateValueAction.prototype._prepare = function () {
  28212. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28213. this._property = this._getProperty(this.propertyPath);
  28214. };
  28215. InterpolateValueAction.prototype.execute = function () {
  28216. var scene = this._actionManager.getScene();
  28217. var keys = [
  28218. {
  28219. frame: 0,
  28220. value: this._target[this._property]
  28221. }, {
  28222. frame: 100,
  28223. value: this.value
  28224. }
  28225. ];
  28226. var dataType;
  28227. if (typeof this.value === "number") {
  28228. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28229. }
  28230. else if (this.value instanceof BABYLON.Color3) {
  28231. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28232. }
  28233. else if (this.value instanceof BABYLON.Vector3) {
  28234. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28235. }
  28236. else if (this.value instanceof BABYLON.Matrix) {
  28237. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28238. }
  28239. else if (this.value instanceof BABYLON.Quaternion) {
  28240. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28241. }
  28242. else {
  28243. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28244. return;
  28245. }
  28246. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28247. animation.setKeys(keys);
  28248. if (this.stopOtherAnimations) {
  28249. scene.stopAnimation(this._target);
  28250. }
  28251. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28252. };
  28253. return InterpolateValueAction;
  28254. })(BABYLON.Action);
  28255. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28256. })(BABYLON || (BABYLON = {}));
  28257. var BABYLON;
  28258. (function (BABYLON) {
  28259. var SwitchBooleanAction = (function (_super) {
  28260. __extends(SwitchBooleanAction, _super);
  28261. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28262. _super.call(this, triggerOptions, condition);
  28263. this.propertyPath = propertyPath;
  28264. this._target = target;
  28265. }
  28266. SwitchBooleanAction.prototype._prepare = function () {
  28267. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28268. this._property = this._getProperty(this.propertyPath);
  28269. };
  28270. SwitchBooleanAction.prototype.execute = function () {
  28271. this._target[this._property] = !this._target[this._property];
  28272. };
  28273. return SwitchBooleanAction;
  28274. })(BABYLON.Action);
  28275. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28276. var SetStateAction = (function (_super) {
  28277. __extends(SetStateAction, _super);
  28278. function SetStateAction(triggerOptions, target, value, condition) {
  28279. _super.call(this, triggerOptions, condition);
  28280. this.value = value;
  28281. this._target = target;
  28282. }
  28283. SetStateAction.prototype.execute = function () {
  28284. this._target.state = this.value;
  28285. };
  28286. return SetStateAction;
  28287. })(BABYLON.Action);
  28288. BABYLON.SetStateAction = SetStateAction;
  28289. var SetValueAction = (function (_super) {
  28290. __extends(SetValueAction, _super);
  28291. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28292. _super.call(this, triggerOptions, condition);
  28293. this.propertyPath = propertyPath;
  28294. this.value = value;
  28295. this._target = target;
  28296. }
  28297. SetValueAction.prototype._prepare = function () {
  28298. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28299. this._property = this._getProperty(this.propertyPath);
  28300. };
  28301. SetValueAction.prototype.execute = function () {
  28302. this._target[this._property] = this.value;
  28303. };
  28304. return SetValueAction;
  28305. })(BABYLON.Action);
  28306. BABYLON.SetValueAction = SetValueAction;
  28307. var IncrementValueAction = (function (_super) {
  28308. __extends(IncrementValueAction, _super);
  28309. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28310. _super.call(this, triggerOptions, condition);
  28311. this.propertyPath = propertyPath;
  28312. this.value = value;
  28313. this._target = target;
  28314. }
  28315. IncrementValueAction.prototype._prepare = function () {
  28316. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28317. this._property = this._getProperty(this.propertyPath);
  28318. if (typeof this._target[this._property] !== "number") {
  28319. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28320. }
  28321. };
  28322. IncrementValueAction.prototype.execute = function () {
  28323. this._target[this._property] += this.value;
  28324. };
  28325. return IncrementValueAction;
  28326. })(BABYLON.Action);
  28327. BABYLON.IncrementValueAction = IncrementValueAction;
  28328. var PlayAnimationAction = (function (_super) {
  28329. __extends(PlayAnimationAction, _super);
  28330. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28331. _super.call(this, triggerOptions, condition);
  28332. this.from = from;
  28333. this.to = to;
  28334. this.loop = loop;
  28335. this._target = target;
  28336. }
  28337. PlayAnimationAction.prototype._prepare = function () {
  28338. };
  28339. PlayAnimationAction.prototype.execute = function () {
  28340. var scene = this._actionManager.getScene();
  28341. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28342. };
  28343. return PlayAnimationAction;
  28344. })(BABYLON.Action);
  28345. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28346. var StopAnimationAction = (function (_super) {
  28347. __extends(StopAnimationAction, _super);
  28348. function StopAnimationAction(triggerOptions, target, condition) {
  28349. _super.call(this, triggerOptions, condition);
  28350. this._target = target;
  28351. }
  28352. StopAnimationAction.prototype._prepare = function () {
  28353. };
  28354. StopAnimationAction.prototype.execute = function () {
  28355. var scene = this._actionManager.getScene();
  28356. scene.stopAnimation(this._target);
  28357. };
  28358. return StopAnimationAction;
  28359. })(BABYLON.Action);
  28360. BABYLON.StopAnimationAction = StopAnimationAction;
  28361. var DoNothingAction = (function (_super) {
  28362. __extends(DoNothingAction, _super);
  28363. function DoNothingAction(triggerOptions, condition) {
  28364. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28365. _super.call(this, triggerOptions, condition);
  28366. }
  28367. DoNothingAction.prototype.execute = function () {
  28368. };
  28369. return DoNothingAction;
  28370. })(BABYLON.Action);
  28371. BABYLON.DoNothingAction = DoNothingAction;
  28372. var CombineAction = (function (_super) {
  28373. __extends(CombineAction, _super);
  28374. function CombineAction(triggerOptions, children, condition) {
  28375. _super.call(this, triggerOptions, condition);
  28376. this.children = children;
  28377. }
  28378. CombineAction.prototype._prepare = function () {
  28379. for (var index = 0; index < this.children.length; index++) {
  28380. this.children[index]._actionManager = this._actionManager;
  28381. this.children[index]._prepare();
  28382. }
  28383. };
  28384. CombineAction.prototype.execute = function (evt) {
  28385. for (var index = 0; index < this.children.length; index++) {
  28386. this.children[index].execute(evt);
  28387. }
  28388. };
  28389. return CombineAction;
  28390. })(BABYLON.Action);
  28391. BABYLON.CombineAction = CombineAction;
  28392. var ExecuteCodeAction = (function (_super) {
  28393. __extends(ExecuteCodeAction, _super);
  28394. function ExecuteCodeAction(triggerOptions, func, condition) {
  28395. _super.call(this, triggerOptions, condition);
  28396. this.func = func;
  28397. }
  28398. ExecuteCodeAction.prototype.execute = function (evt) {
  28399. this.func(evt);
  28400. };
  28401. return ExecuteCodeAction;
  28402. })(BABYLON.Action);
  28403. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28404. var SetParentAction = (function (_super) {
  28405. __extends(SetParentAction, _super);
  28406. function SetParentAction(triggerOptions, target, parent, condition) {
  28407. _super.call(this, triggerOptions, condition);
  28408. this._target = target;
  28409. this._parent = parent;
  28410. }
  28411. SetParentAction.prototype._prepare = function () {
  28412. };
  28413. SetParentAction.prototype.execute = function () {
  28414. if (this._target.parent === this._parent) {
  28415. return;
  28416. }
  28417. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28418. invertParentWorldMatrix.invert();
  28419. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28420. this._target.parent = this._parent;
  28421. };
  28422. return SetParentAction;
  28423. })(BABYLON.Action);
  28424. BABYLON.SetParentAction = SetParentAction;
  28425. var PlaySoundAction = (function (_super) {
  28426. __extends(PlaySoundAction, _super);
  28427. function PlaySoundAction(triggerOptions, sound, condition) {
  28428. _super.call(this, triggerOptions, condition);
  28429. this._sound = sound;
  28430. }
  28431. PlaySoundAction.prototype._prepare = function () {
  28432. };
  28433. PlaySoundAction.prototype.execute = function () {
  28434. if (this._sound !== undefined)
  28435. this._sound.play();
  28436. };
  28437. return PlaySoundAction;
  28438. })(BABYLON.Action);
  28439. BABYLON.PlaySoundAction = PlaySoundAction;
  28440. var StopSoundAction = (function (_super) {
  28441. __extends(StopSoundAction, _super);
  28442. function StopSoundAction(triggerOptions, sound, condition) {
  28443. _super.call(this, triggerOptions, condition);
  28444. this._sound = sound;
  28445. }
  28446. StopSoundAction.prototype._prepare = function () {
  28447. };
  28448. StopSoundAction.prototype.execute = function () {
  28449. if (this._sound !== undefined)
  28450. this._sound.stop();
  28451. };
  28452. return StopSoundAction;
  28453. })(BABYLON.Action);
  28454. BABYLON.StopSoundAction = StopSoundAction;
  28455. })(BABYLON || (BABYLON = {}));
  28456. var BABYLON;
  28457. (function (BABYLON) {
  28458. var Geometry = (function () {
  28459. function Geometry(id, scene, vertexData, updatable, mesh) {
  28460. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28461. this._totalVertices = 0;
  28462. this._indices = [];
  28463. this._isDisposed = false;
  28464. this.id = id;
  28465. this._engine = scene.getEngine();
  28466. this._meshes = [];
  28467. this._scene = scene;
  28468. // vertexData
  28469. if (vertexData) {
  28470. this.setAllVerticesData(vertexData, updatable);
  28471. }
  28472. else {
  28473. this._totalVertices = 0;
  28474. this._indices = [];
  28475. }
  28476. // applyToMesh
  28477. if (mesh) {
  28478. this.applyToMesh(mesh);
  28479. mesh.computeWorldMatrix(true);
  28480. }
  28481. }
  28482. Geometry.prototype.getScene = function () {
  28483. return this._scene;
  28484. };
  28485. Geometry.prototype.getEngine = function () {
  28486. return this._engine;
  28487. };
  28488. Geometry.prototype.isReady = function () {
  28489. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28490. };
  28491. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28492. vertexData.applyToGeometry(this, updatable);
  28493. this.notifyUpdate();
  28494. };
  28495. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28496. this._vertexBuffers = this._vertexBuffers || {};
  28497. if (this._vertexBuffers[kind]) {
  28498. this._vertexBuffers[kind].dispose();
  28499. }
  28500. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28501. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28502. stride = this._vertexBuffers[kind].getStrideSize();
  28503. this._totalVertices = data.length / stride;
  28504. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28505. var meshes = this._meshes;
  28506. var numOfMeshes = meshes.length;
  28507. for (var index = 0; index < numOfMeshes; index++) {
  28508. var mesh = meshes[index];
  28509. mesh._resetPointsArrayCache();
  28510. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28511. mesh._createGlobalSubMesh();
  28512. mesh.computeWorldMatrix(true);
  28513. }
  28514. }
  28515. this.notifyUpdate(kind);
  28516. };
  28517. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28518. var vertexBuffer = this.getVertexBuffer(kind);
  28519. if (!vertexBuffer) {
  28520. return;
  28521. }
  28522. vertexBuffer.updateDirectly(data, offset);
  28523. this.notifyUpdate(kind);
  28524. };
  28525. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28526. var vertexBuffer = this.getVertexBuffer(kind);
  28527. if (!vertexBuffer) {
  28528. return;
  28529. }
  28530. vertexBuffer.update(data);
  28531. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28532. var extend;
  28533. var stride = vertexBuffer.getStrideSize();
  28534. this._totalVertices = data.length / stride;
  28535. if (updateExtends) {
  28536. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28537. }
  28538. var meshes = this._meshes;
  28539. var numOfMeshes = meshes.length;
  28540. for (var index = 0; index < numOfMeshes; index++) {
  28541. var mesh = meshes[index];
  28542. mesh._resetPointsArrayCache();
  28543. if (updateExtends) {
  28544. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28545. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28546. var subMesh = mesh.subMeshes[subIndex];
  28547. subMesh.refreshBoundingInfo();
  28548. }
  28549. }
  28550. }
  28551. }
  28552. this.notifyUpdate(kind);
  28553. };
  28554. Geometry.prototype.getTotalVertices = function () {
  28555. if (!this.isReady()) {
  28556. return 0;
  28557. }
  28558. return this._totalVertices;
  28559. };
  28560. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28561. var vertexBuffer = this.getVertexBuffer(kind);
  28562. if (!vertexBuffer) {
  28563. return null;
  28564. }
  28565. var orig = vertexBuffer.getData();
  28566. if (!copyWhenShared || this._meshes.length === 1) {
  28567. return orig;
  28568. }
  28569. else {
  28570. var len = orig.length;
  28571. var copy = [];
  28572. for (var i = 0; i < len; i++) {
  28573. copy.push(orig[i]);
  28574. }
  28575. return copy;
  28576. }
  28577. };
  28578. Geometry.prototype.getVertexBuffer = function (kind) {
  28579. if (!this.isReady()) {
  28580. return null;
  28581. }
  28582. return this._vertexBuffers[kind];
  28583. };
  28584. Geometry.prototype.getVertexBuffers = function () {
  28585. if (!this.isReady()) {
  28586. return null;
  28587. }
  28588. return this._vertexBuffers;
  28589. };
  28590. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28591. if (!this._vertexBuffers) {
  28592. if (this._delayInfo) {
  28593. return this._delayInfo.indexOf(kind) !== -1;
  28594. }
  28595. return false;
  28596. }
  28597. return this._vertexBuffers[kind] !== undefined;
  28598. };
  28599. Geometry.prototype.getVerticesDataKinds = function () {
  28600. var result = [];
  28601. if (!this._vertexBuffers && this._delayInfo) {
  28602. for (var kind in this._delayInfo) {
  28603. result.push(kind);
  28604. }
  28605. }
  28606. else {
  28607. for (kind in this._vertexBuffers) {
  28608. result.push(kind);
  28609. }
  28610. }
  28611. return result;
  28612. };
  28613. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28614. if (this._indexBuffer) {
  28615. this._engine._releaseBuffer(this._indexBuffer);
  28616. }
  28617. this._indices = indices;
  28618. if (this._meshes.length !== 0 && this._indices) {
  28619. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28620. }
  28621. if (totalVertices !== undefined) {
  28622. this._totalVertices = totalVertices;
  28623. }
  28624. var meshes = this._meshes;
  28625. var numOfMeshes = meshes.length;
  28626. for (var index = 0; index < numOfMeshes; index++) {
  28627. meshes[index]._createGlobalSubMesh();
  28628. }
  28629. this.notifyUpdate();
  28630. };
  28631. Geometry.prototype.getTotalIndices = function () {
  28632. if (!this.isReady()) {
  28633. return 0;
  28634. }
  28635. return this._indices.length;
  28636. };
  28637. Geometry.prototype.getIndices = function (copyWhenShared) {
  28638. if (!this.isReady()) {
  28639. return null;
  28640. }
  28641. var orig = this._indices;
  28642. if (!copyWhenShared || this._meshes.length === 1) {
  28643. return orig;
  28644. }
  28645. else {
  28646. var len = orig.length;
  28647. var copy = [];
  28648. for (var i = 0; i < len; i++) {
  28649. copy.push(orig[i]);
  28650. }
  28651. return copy;
  28652. }
  28653. };
  28654. Geometry.prototype.getIndexBuffer = function () {
  28655. if (!this.isReady()) {
  28656. return null;
  28657. }
  28658. return this._indexBuffer;
  28659. };
  28660. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28661. var meshes = this._meshes;
  28662. var index = meshes.indexOf(mesh);
  28663. if (index === -1) {
  28664. return;
  28665. }
  28666. for (var kind in this._vertexBuffers) {
  28667. this._vertexBuffers[kind].dispose();
  28668. }
  28669. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28670. this._indexBuffer = null;
  28671. }
  28672. meshes.splice(index, 1);
  28673. mesh._geometry = null;
  28674. if (meshes.length === 0 && shouldDispose) {
  28675. this.dispose();
  28676. }
  28677. };
  28678. Geometry.prototype.applyToMesh = function (mesh) {
  28679. if (mesh._geometry === this) {
  28680. return;
  28681. }
  28682. var previousGeometry = mesh._geometry;
  28683. if (previousGeometry) {
  28684. previousGeometry.releaseForMesh(mesh);
  28685. }
  28686. var meshes = this._meshes;
  28687. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28688. mesh._geometry = this;
  28689. this._scene.pushGeometry(this);
  28690. meshes.push(mesh);
  28691. if (this.isReady()) {
  28692. this._applyToMesh(mesh);
  28693. }
  28694. else {
  28695. mesh._boundingInfo = this._boundingInfo;
  28696. }
  28697. };
  28698. Geometry.prototype._applyToMesh = function (mesh) {
  28699. var numOfMeshes = this._meshes.length;
  28700. // vertexBuffers
  28701. for (var kind in this._vertexBuffers) {
  28702. if (numOfMeshes === 1) {
  28703. this._vertexBuffers[kind].create();
  28704. }
  28705. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28706. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28707. mesh._resetPointsArrayCache();
  28708. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28709. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28710. mesh._createGlobalSubMesh();
  28711. //bounding info was just created again, world matrix should be applied again.
  28712. mesh._updateBoundingInfo();
  28713. }
  28714. }
  28715. // indexBuffer
  28716. if (numOfMeshes === 1 && this._indices) {
  28717. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28718. }
  28719. if (this._indexBuffer) {
  28720. this._indexBuffer.references = numOfMeshes;
  28721. }
  28722. };
  28723. Geometry.prototype.notifyUpdate = function (kind) {
  28724. if (this.onGeometryUpdated) {
  28725. this.onGeometryUpdated(this, kind);
  28726. }
  28727. };
  28728. Geometry.prototype.load = function (scene, onLoaded) {
  28729. var _this = this;
  28730. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28731. return;
  28732. }
  28733. if (this.isReady()) {
  28734. if (onLoaded) {
  28735. onLoaded();
  28736. }
  28737. return;
  28738. }
  28739. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28740. scene._addPendingData(this);
  28741. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28742. _this._delayLoadingFunction(JSON.parse(data), _this);
  28743. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28744. _this._delayInfo = [];
  28745. scene._removePendingData(_this);
  28746. var meshes = _this._meshes;
  28747. var numOfMeshes = meshes.length;
  28748. for (var index = 0; index < numOfMeshes; index++) {
  28749. _this._applyToMesh(meshes[index]);
  28750. }
  28751. if (onLoaded) {
  28752. onLoaded();
  28753. }
  28754. }, function () { }, scene.database);
  28755. };
  28756. Geometry.prototype.isDisposed = function () {
  28757. return this._isDisposed;
  28758. };
  28759. Geometry.prototype.dispose = function () {
  28760. var meshes = this._meshes;
  28761. var numOfMeshes = meshes.length;
  28762. var index;
  28763. for (index = 0; index < numOfMeshes; index++) {
  28764. this.releaseForMesh(meshes[index]);
  28765. }
  28766. this._meshes = [];
  28767. for (var kind in this._vertexBuffers) {
  28768. this._vertexBuffers[kind].dispose();
  28769. }
  28770. this._vertexBuffers = [];
  28771. this._totalVertices = 0;
  28772. if (this._indexBuffer) {
  28773. this._engine._releaseBuffer(this._indexBuffer);
  28774. }
  28775. this._indexBuffer = null;
  28776. this._indices = [];
  28777. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28778. this.delayLoadingFile = null;
  28779. this._delayLoadingFunction = null;
  28780. this._delayInfo = [];
  28781. this._boundingInfo = null; // todo: .dispose()
  28782. this._scene.removeGeometry(this);
  28783. this._isDisposed = true;
  28784. };
  28785. Geometry.prototype.copy = function (id) {
  28786. var vertexData = new BABYLON.VertexData();
  28787. vertexData.indices = [];
  28788. var indices = this.getIndices();
  28789. for (var index = 0; index < indices.length; index++) {
  28790. vertexData.indices.push(indices[index]);
  28791. }
  28792. var updatable = false;
  28793. var stopChecking = false;
  28794. for (var kind in this._vertexBuffers) {
  28795. // using slice() to make a copy of the array and not just reference it
  28796. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28797. if (!stopChecking) {
  28798. updatable = this.getVertexBuffer(kind).isUpdatable();
  28799. stopChecking = !updatable;
  28800. }
  28801. }
  28802. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28803. geometry.delayLoadState = this.delayLoadState;
  28804. geometry.delayLoadingFile = this.delayLoadingFile;
  28805. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28806. for (kind in this._delayInfo) {
  28807. geometry._delayInfo = geometry._delayInfo || [];
  28808. geometry._delayInfo.push(kind);
  28809. }
  28810. // Bounding info
  28811. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28812. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28813. return geometry;
  28814. };
  28815. // Statics
  28816. Geometry.ExtractFromMesh = function (mesh, id) {
  28817. var geometry = mesh._geometry;
  28818. if (!geometry) {
  28819. return null;
  28820. }
  28821. return geometry.copy(id);
  28822. };
  28823. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28824. // be aware Math.random() could cause collisions
  28825. Geometry.RandomId = function () {
  28826. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28827. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28828. return v.toString(16);
  28829. });
  28830. };
  28831. return Geometry;
  28832. })();
  28833. BABYLON.Geometry = Geometry;
  28834. /////// Primitives //////////////////////////////////////////////
  28835. var Geometry;
  28836. (function (Geometry) {
  28837. var Primitives;
  28838. (function (Primitives) {
  28839. /// Abstract class
  28840. var _Primitive = (function (_super) {
  28841. __extends(_Primitive, _super);
  28842. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28843. this._beingRegenerated = true;
  28844. this._canBeRegenerated = canBeRegenerated;
  28845. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28846. this._beingRegenerated = false;
  28847. }
  28848. _Primitive.prototype.canBeRegenerated = function () {
  28849. return this._canBeRegenerated;
  28850. };
  28851. _Primitive.prototype.regenerate = function () {
  28852. if (!this._canBeRegenerated) {
  28853. return;
  28854. }
  28855. this._beingRegenerated = true;
  28856. this.setAllVerticesData(this._regenerateVertexData(), false);
  28857. this._beingRegenerated = false;
  28858. };
  28859. _Primitive.prototype.asNewGeometry = function (id) {
  28860. return _super.prototype.copy.call(this, id);
  28861. };
  28862. // overrides
  28863. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28864. if (!this._beingRegenerated) {
  28865. return;
  28866. }
  28867. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28868. };
  28869. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28870. if (!this._beingRegenerated) {
  28871. return;
  28872. }
  28873. _super.prototype.setVerticesData.call(this, kind, data, false);
  28874. };
  28875. // to override
  28876. // protected
  28877. _Primitive.prototype._regenerateVertexData = function () {
  28878. throw new Error("Abstract method");
  28879. };
  28880. _Primitive.prototype.copy = function (id) {
  28881. throw new Error("Must be overriden in sub-classes.");
  28882. };
  28883. return _Primitive;
  28884. })(Geometry);
  28885. Primitives._Primitive = _Primitive;
  28886. var Ribbon = (function (_super) {
  28887. __extends(Ribbon, _super);
  28888. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28889. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28890. this.pathArray = pathArray;
  28891. this.closeArray = closeArray;
  28892. this.closePath = closePath;
  28893. this.offset = offset;
  28894. this.side = side;
  28895. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28896. }
  28897. Ribbon.prototype._regenerateVertexData = function () {
  28898. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28899. };
  28900. Ribbon.prototype.copy = function (id) {
  28901. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28902. };
  28903. return Ribbon;
  28904. })(_Primitive);
  28905. Primitives.Ribbon = Ribbon;
  28906. var Box = (function (_super) {
  28907. __extends(Box, _super);
  28908. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28909. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28910. this.size = size;
  28911. this.side = side;
  28912. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28913. }
  28914. Box.prototype._regenerateVertexData = function () {
  28915. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28916. };
  28917. Box.prototype.copy = function (id) {
  28918. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28919. };
  28920. return Box;
  28921. })(_Primitive);
  28922. Primitives.Box = Box;
  28923. var Sphere = (function (_super) {
  28924. __extends(Sphere, _super);
  28925. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28926. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28927. this.segments = segments;
  28928. this.diameter = diameter;
  28929. this.side = side;
  28930. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28931. }
  28932. Sphere.prototype._regenerateVertexData = function () {
  28933. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28934. };
  28935. Sphere.prototype.copy = function (id) {
  28936. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28937. };
  28938. return Sphere;
  28939. })(_Primitive);
  28940. Primitives.Sphere = Sphere;
  28941. var Cylinder = (function (_super) {
  28942. __extends(Cylinder, _super);
  28943. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28944. if (subdivisions === void 0) { subdivisions = 1; }
  28945. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28946. this.height = height;
  28947. this.diameterTop = diameterTop;
  28948. this.diameterBottom = diameterBottom;
  28949. this.tessellation = tessellation;
  28950. this.subdivisions = subdivisions;
  28951. this.side = side;
  28952. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28953. }
  28954. Cylinder.prototype._regenerateVertexData = function () {
  28955. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  28956. };
  28957. Cylinder.prototype.copy = function (id) {
  28958. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28959. };
  28960. return Cylinder;
  28961. })(_Primitive);
  28962. Primitives.Cylinder = Cylinder;
  28963. var Torus = (function (_super) {
  28964. __extends(Torus, _super);
  28965. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28966. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28967. this.diameter = diameter;
  28968. this.thickness = thickness;
  28969. this.tessellation = tessellation;
  28970. this.side = side;
  28971. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28972. }
  28973. Torus.prototype._regenerateVertexData = function () {
  28974. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  28975. };
  28976. Torus.prototype.copy = function (id) {
  28977. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28978. };
  28979. return Torus;
  28980. })(_Primitive);
  28981. Primitives.Torus = Torus;
  28982. var Ground = (function (_super) {
  28983. __extends(Ground, _super);
  28984. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28985. this.width = width;
  28986. this.height = height;
  28987. this.subdivisions = subdivisions;
  28988. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28989. }
  28990. Ground.prototype._regenerateVertexData = function () {
  28991. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  28992. };
  28993. Ground.prototype.copy = function (id) {
  28994. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28995. };
  28996. return Ground;
  28997. })(_Primitive);
  28998. Primitives.Ground = Ground;
  28999. var TiledGround = (function (_super) {
  29000. __extends(TiledGround, _super);
  29001. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29002. this.xmin = xmin;
  29003. this.zmin = zmin;
  29004. this.xmax = xmax;
  29005. this.zmax = zmax;
  29006. this.subdivisions = subdivisions;
  29007. this.precision = precision;
  29008. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29009. }
  29010. TiledGround.prototype._regenerateVertexData = function () {
  29011. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  29012. };
  29013. TiledGround.prototype.copy = function (id) {
  29014. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29015. };
  29016. return TiledGround;
  29017. })(_Primitive);
  29018. Primitives.TiledGround = TiledGround;
  29019. var Plane = (function (_super) {
  29020. __extends(Plane, _super);
  29021. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29023. this.size = size;
  29024. this.side = side;
  29025. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29026. }
  29027. Plane.prototype._regenerateVertexData = function () {
  29028. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  29029. };
  29030. Plane.prototype.copy = function (id) {
  29031. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29032. };
  29033. return Plane;
  29034. })(_Primitive);
  29035. Primitives.Plane = Plane;
  29036. var TorusKnot = (function (_super) {
  29037. __extends(TorusKnot, _super);
  29038. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29039. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29040. this.radius = radius;
  29041. this.tube = tube;
  29042. this.radialSegments = radialSegments;
  29043. this.tubularSegments = tubularSegments;
  29044. this.p = p;
  29045. this.q = q;
  29046. this.side = side;
  29047. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29048. }
  29049. TorusKnot.prototype._regenerateVertexData = function () {
  29050. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  29051. };
  29052. TorusKnot.prototype.copy = function (id) {
  29053. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29054. };
  29055. return TorusKnot;
  29056. })(_Primitive);
  29057. Primitives.TorusKnot = TorusKnot;
  29058. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29059. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29060. })(BABYLON || (BABYLON = {}));
  29061. var BABYLON;
  29062. (function (BABYLON) {
  29063. var GroundMesh = (function (_super) {
  29064. __extends(GroundMesh, _super);
  29065. function GroundMesh(name, scene) {
  29066. _super.call(this, name, scene);
  29067. this.generateOctree = false;
  29068. this._worldInverse = new BABYLON.Matrix();
  29069. }
  29070. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29071. get: function () {
  29072. return this._subdivisions;
  29073. },
  29074. enumerable: true,
  29075. configurable: true
  29076. });
  29077. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29078. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29079. this._subdivisions = chunksCount;
  29080. this.subdivide(this._subdivisions);
  29081. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29082. };
  29083. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29084. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29085. this.getWorldMatrix().invertToRef(this._worldInverse);
  29086. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29087. var pickInfo = this.intersects(ray);
  29088. if (pickInfo.hit) {
  29089. return pickInfo.pickedPoint.y;
  29090. }
  29091. return 0;
  29092. };
  29093. return GroundMesh;
  29094. })(BABYLON.Mesh);
  29095. BABYLON.GroundMesh = GroundMesh;
  29096. })(BABYLON || (BABYLON = {}));
  29097. var BABYLON;
  29098. (function (BABYLON) {
  29099. var LinesMesh = (function (_super) {
  29100. __extends(LinesMesh, _super);
  29101. function LinesMesh(name, scene, updatable) {
  29102. if (updatable === void 0) { updatable = false; }
  29103. _super.call(this, name, scene);
  29104. this.color = new BABYLON.Color3(1, 1, 1);
  29105. this.alpha = 1;
  29106. this._indices = new Array();
  29107. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29108. attributes: ["position"],
  29109. uniforms: ["worldViewProjection", "color"],
  29110. needAlphaBlending: true
  29111. });
  29112. }
  29113. Object.defineProperty(LinesMesh.prototype, "material", {
  29114. get: function () {
  29115. return this._colorShader;
  29116. },
  29117. enumerable: true,
  29118. configurable: true
  29119. });
  29120. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29121. get: function () {
  29122. return false;
  29123. },
  29124. enumerable: true,
  29125. configurable: true
  29126. });
  29127. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29128. get: function () {
  29129. return false;
  29130. },
  29131. enumerable: true,
  29132. configurable: true
  29133. });
  29134. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29135. var engine = this.getScene().getEngine();
  29136. var indexToBind = this._geometry.getIndexBuffer();
  29137. // VBOs
  29138. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29139. // Color
  29140. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29141. };
  29142. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29143. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29144. return;
  29145. }
  29146. var engine = this.getScene().getEngine();
  29147. // Draw order
  29148. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29149. };
  29150. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29151. return null;
  29152. };
  29153. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29154. this._colorShader.dispose();
  29155. _super.prototype.dispose.call(this, doNotRecurse);
  29156. };
  29157. return LinesMesh;
  29158. })(BABYLON.Mesh);
  29159. BABYLON.LinesMesh = LinesMesh;
  29160. })(BABYLON || (BABYLON = {}));
  29161. var BABYLON;
  29162. (function (BABYLON) {
  29163. var OutlineRenderer = (function () {
  29164. function OutlineRenderer(scene) {
  29165. this._scene = scene;
  29166. }
  29167. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29168. var _this = this;
  29169. if (useOverlay === void 0) { useOverlay = false; }
  29170. var scene = this._scene;
  29171. var engine = this._scene.getEngine();
  29172. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29173. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29174. return;
  29175. }
  29176. var mesh = subMesh.getRenderingMesh();
  29177. var material = subMesh.getMaterial();
  29178. engine.enableEffect(this._effect);
  29179. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29180. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29181. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29182. // Bones
  29183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29184. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29185. }
  29186. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29187. // Alpha test
  29188. if (material && material.needAlphaTesting()) {
  29189. var alphaTexture = material.getAlphaTestTexture();
  29190. this._effect.setTexture("diffuseSampler", alphaTexture);
  29191. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29192. }
  29193. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29194. };
  29195. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29196. var defines = [];
  29197. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29198. var mesh = subMesh.getMesh();
  29199. var material = subMesh.getMaterial();
  29200. // Alpha test
  29201. if (material && material.needAlphaTesting()) {
  29202. defines.push("#define ALPHATEST");
  29203. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29204. attribs.push(BABYLON.VertexBuffer.UVKind);
  29205. defines.push("#define UV1");
  29206. }
  29207. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29208. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29209. defines.push("#define UV2");
  29210. }
  29211. }
  29212. // Bones
  29213. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29214. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29215. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29216. defines.push("#define BONES");
  29217. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29218. }
  29219. // Instances
  29220. if (useInstances) {
  29221. defines.push("#define INSTANCES");
  29222. attribs.push("world0");
  29223. attribs.push("world1");
  29224. attribs.push("world2");
  29225. attribs.push("world3");
  29226. }
  29227. // Get correct effect
  29228. var join = defines.join("\n");
  29229. if (this._cachedDefines !== join) {
  29230. this._cachedDefines = join;
  29231. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29232. }
  29233. return this._effect.isReady();
  29234. };
  29235. return OutlineRenderer;
  29236. })();
  29237. BABYLON.OutlineRenderer = OutlineRenderer;
  29238. })(BABYLON || (BABYLON = {}));
  29239. var BABYLON;
  29240. (function (BABYLON) {
  29241. var MeshAssetTask = (function () {
  29242. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29243. this.name = name;
  29244. this.meshesNames = meshesNames;
  29245. this.rootUrl = rootUrl;
  29246. this.sceneFilename = sceneFilename;
  29247. this.isCompleted = false;
  29248. }
  29249. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29250. var _this = this;
  29251. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29252. _this.loadedMeshes = meshes;
  29253. _this.loadedParticleSystems = particleSystems;
  29254. _this.loadedSkeletons = skeletons;
  29255. _this.isCompleted = true;
  29256. if (_this.onSuccess) {
  29257. _this.onSuccess(_this);
  29258. }
  29259. onSuccess();
  29260. }, null, function () {
  29261. if (_this.onError) {
  29262. _this.onError(_this);
  29263. }
  29264. onError();
  29265. });
  29266. };
  29267. return MeshAssetTask;
  29268. })();
  29269. BABYLON.MeshAssetTask = MeshAssetTask;
  29270. var TextFileAssetTask = (function () {
  29271. function TextFileAssetTask(name, url) {
  29272. this.name = name;
  29273. this.url = url;
  29274. this.isCompleted = false;
  29275. }
  29276. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29277. var _this = this;
  29278. BABYLON.Tools.LoadFile(this.url, function (data) {
  29279. _this.text = data;
  29280. _this.isCompleted = true;
  29281. if (_this.onSuccess) {
  29282. _this.onSuccess(_this);
  29283. }
  29284. onSuccess();
  29285. }, null, scene.database, false, function () {
  29286. if (_this.onError) {
  29287. _this.onError(_this);
  29288. }
  29289. onError();
  29290. });
  29291. };
  29292. return TextFileAssetTask;
  29293. })();
  29294. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29295. var BinaryFileAssetTask = (function () {
  29296. function BinaryFileAssetTask(name, url) {
  29297. this.name = name;
  29298. this.url = url;
  29299. this.isCompleted = false;
  29300. }
  29301. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29302. var _this = this;
  29303. BABYLON.Tools.LoadFile(this.url, function (data) {
  29304. _this.data = data;
  29305. _this.isCompleted = true;
  29306. if (_this.onSuccess) {
  29307. _this.onSuccess(_this);
  29308. }
  29309. onSuccess();
  29310. }, null, scene.database, true, function () {
  29311. if (_this.onError) {
  29312. _this.onError(_this);
  29313. }
  29314. onError();
  29315. });
  29316. };
  29317. return BinaryFileAssetTask;
  29318. })();
  29319. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29320. var ImageAssetTask = (function () {
  29321. function ImageAssetTask(name, url) {
  29322. this.name = name;
  29323. this.url = url;
  29324. this.isCompleted = false;
  29325. }
  29326. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29327. var _this = this;
  29328. var img = new Image();
  29329. img.onload = function () {
  29330. _this.image = img;
  29331. _this.isCompleted = true;
  29332. if (_this.onSuccess) {
  29333. _this.onSuccess(_this);
  29334. }
  29335. onSuccess();
  29336. };
  29337. img.onerror = function () {
  29338. if (_this.onError) {
  29339. _this.onError(_this);
  29340. }
  29341. onError();
  29342. };
  29343. img.src = this.url;
  29344. };
  29345. return ImageAssetTask;
  29346. })();
  29347. BABYLON.ImageAssetTask = ImageAssetTask;
  29348. var TextureAssetTask = (function () {
  29349. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29351. this.name = name;
  29352. this.url = url;
  29353. this.noMipmap = noMipmap;
  29354. this.invertY = invertY;
  29355. this.samplingMode = samplingMode;
  29356. this.isCompleted = false;
  29357. }
  29358. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29359. var _this = this;
  29360. var onload = function () {
  29361. _this.isCompleted = true;
  29362. if (_this.onSuccess) {
  29363. _this.onSuccess(_this);
  29364. }
  29365. onSuccess();
  29366. };
  29367. var onerror = function () {
  29368. if (_this.onError) {
  29369. _this.onError(_this);
  29370. }
  29371. onError();
  29372. };
  29373. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29374. };
  29375. return TextureAssetTask;
  29376. })();
  29377. BABYLON.TextureAssetTask = TextureAssetTask;
  29378. var AssetsManager = (function () {
  29379. function AssetsManager(scene) {
  29380. this._tasks = new Array();
  29381. this._waitingTasksCount = 0;
  29382. this.useDefaultLoadingScreen = true;
  29383. this._scene = scene;
  29384. }
  29385. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29386. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29387. this._tasks.push(task);
  29388. return task;
  29389. };
  29390. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29391. var task = new TextFileAssetTask(taskName, url);
  29392. this._tasks.push(task);
  29393. return task;
  29394. };
  29395. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29396. var task = new BinaryFileAssetTask(taskName, url);
  29397. this._tasks.push(task);
  29398. return task;
  29399. };
  29400. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29401. var task = new ImageAssetTask(taskName, url);
  29402. this._tasks.push(task);
  29403. return task;
  29404. };
  29405. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29407. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29408. this._tasks.push(task);
  29409. return task;
  29410. };
  29411. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29412. this._waitingTasksCount--;
  29413. if (this._waitingTasksCount === 0) {
  29414. if (this.onFinish) {
  29415. this.onFinish(this._tasks);
  29416. }
  29417. this._scene.getEngine().hideLoadingUI();
  29418. }
  29419. };
  29420. AssetsManager.prototype._runTask = function (task) {
  29421. var _this = this;
  29422. task.run(this._scene, function () {
  29423. if (_this.onTaskSuccess) {
  29424. _this.onTaskSuccess(task);
  29425. }
  29426. _this._decreaseWaitingTasksCount();
  29427. }, function () {
  29428. if (_this.onTaskError) {
  29429. _this.onTaskError(task);
  29430. }
  29431. _this._decreaseWaitingTasksCount();
  29432. });
  29433. };
  29434. AssetsManager.prototype.reset = function () {
  29435. this._tasks = new Array();
  29436. return this;
  29437. };
  29438. AssetsManager.prototype.load = function () {
  29439. this._waitingTasksCount = this._tasks.length;
  29440. if (this._waitingTasksCount === 0) {
  29441. if (this.onFinish) {
  29442. this.onFinish(this._tasks);
  29443. }
  29444. return this;
  29445. }
  29446. if (this.useDefaultLoadingScreen) {
  29447. this._scene.getEngine().displayLoadingUI();
  29448. }
  29449. for (var index = 0; index < this._tasks.length; index++) {
  29450. var task = this._tasks[index];
  29451. this._runTask(task);
  29452. }
  29453. return this;
  29454. };
  29455. return AssetsManager;
  29456. })();
  29457. BABYLON.AssetsManager = AssetsManager;
  29458. })(BABYLON || (BABYLON = {}));
  29459. var BABYLON;
  29460. (function (BABYLON) {
  29461. var VRDeviceOrientationFreeCamera = (function (_super) {
  29462. __extends(VRDeviceOrientationFreeCamera, _super);
  29463. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29464. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29465. _super.call(this, name, position, scene);
  29466. this._alpha = 0;
  29467. this._beta = 0;
  29468. this._gamma = 0;
  29469. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29470. metrics.compensateDistorsion = compensateDistorsion;
  29471. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29472. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29473. }
  29474. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29475. this._alpha = +evt.alpha | 0;
  29476. this._beta = +evt.beta | 0;
  29477. this._gamma = +evt.gamma | 0;
  29478. if (this._gamma < 0) {
  29479. this._gamma = 90 + this._gamma;
  29480. }
  29481. else {
  29482. // Incline it in the correct angle.
  29483. this._gamma = 270 - this._gamma;
  29484. }
  29485. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29486. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29487. this.rotation.z = this._beta / 180.0 * Math.PI;
  29488. };
  29489. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29490. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29491. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29492. };
  29493. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29494. _super.prototype.detachControl.call(this, element);
  29495. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29496. };
  29497. return VRDeviceOrientationFreeCamera;
  29498. })(BABYLON.FreeCamera);
  29499. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29500. })(BABYLON || (BABYLON = {}));
  29501. var BABYLON;
  29502. (function (BABYLON) {
  29503. var WebVRFreeCamera = (function (_super) {
  29504. __extends(WebVRFreeCamera, _super);
  29505. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29506. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29507. _super.call(this, name, position, scene);
  29508. this._hmdDevice = null;
  29509. this._sensorDevice = null;
  29510. this._cacheState = null;
  29511. this._cacheQuaternion = new BABYLON.Quaternion();
  29512. this._cacheRotation = BABYLON.Vector3.Zero();
  29513. this._vrEnabled = false;
  29514. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29515. metrics.compensateDistorsion = compensateDistorsion;
  29516. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29517. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29518. }
  29519. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29520. var size = devices.length;
  29521. var i = 0;
  29522. // Reset devices.
  29523. this._sensorDevice = null;
  29524. this._hmdDevice = null;
  29525. // Search for a HmdDevice.
  29526. while (i < size && this._hmdDevice === null) {
  29527. if (devices[i] instanceof HMDVRDevice) {
  29528. this._hmdDevice = devices[i];
  29529. }
  29530. i++;
  29531. }
  29532. i = 0;
  29533. while (i < size && this._sensorDevice === null) {
  29534. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29535. this._sensorDevice = devices[i];
  29536. }
  29537. i++;
  29538. }
  29539. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29540. };
  29541. WebVRFreeCamera.prototype._checkInputs = function () {
  29542. if (this._vrEnabled) {
  29543. this._cacheState = this._sensorDevice.getState();
  29544. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29545. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29546. this.rotation.x = -this._cacheRotation.z;
  29547. this.rotation.y = -this._cacheRotation.y;
  29548. this.rotation.z = this._cacheRotation.x;
  29549. }
  29550. _super.prototype._checkInputs.call(this);
  29551. };
  29552. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29553. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29554. if (navigator.getVRDevices) {
  29555. navigator.getVRDevices().then(this._getWebVRDevices);
  29556. }
  29557. else if (navigator.mozGetVRDevices) {
  29558. navigator.mozGetVRDevices(this._getWebVRDevices);
  29559. }
  29560. };
  29561. WebVRFreeCamera.prototype.detachControl = function (element) {
  29562. _super.prototype.detachControl.call(this, element);
  29563. this._vrEnabled = false;
  29564. };
  29565. return WebVRFreeCamera;
  29566. })(BABYLON.FreeCamera);
  29567. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29568. })(BABYLON || (BABYLON = {}));
  29569. var BABYLON;
  29570. (function (BABYLON) {
  29571. // Standard optimizations
  29572. var SceneOptimization = (function () {
  29573. function SceneOptimization(priority) {
  29574. if (priority === void 0) { priority = 0; }
  29575. this.priority = priority;
  29576. this.apply = function (scene) {
  29577. return true; // Return true if everything that can be done was applied
  29578. };
  29579. }
  29580. return SceneOptimization;
  29581. })();
  29582. BABYLON.SceneOptimization = SceneOptimization;
  29583. var TextureOptimization = (function (_super) {
  29584. __extends(TextureOptimization, _super);
  29585. function TextureOptimization(priority, maximumSize) {
  29586. var _this = this;
  29587. if (priority === void 0) { priority = 0; }
  29588. if (maximumSize === void 0) { maximumSize = 1024; }
  29589. _super.call(this, priority);
  29590. this.priority = priority;
  29591. this.maximumSize = maximumSize;
  29592. this.apply = function (scene) {
  29593. var allDone = true;
  29594. for (var index = 0; index < scene.textures.length; index++) {
  29595. var texture = scene.textures[index];
  29596. if (!texture.canRescale) {
  29597. continue;
  29598. }
  29599. var currentSize = texture.getSize();
  29600. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29601. if (maxDimension > _this.maximumSize) {
  29602. texture.scale(0.5);
  29603. allDone = false;
  29604. }
  29605. }
  29606. return allDone;
  29607. };
  29608. }
  29609. return TextureOptimization;
  29610. })(SceneOptimization);
  29611. BABYLON.TextureOptimization = TextureOptimization;
  29612. var HardwareScalingOptimization = (function (_super) {
  29613. __extends(HardwareScalingOptimization, _super);
  29614. function HardwareScalingOptimization(priority, maximumScale) {
  29615. var _this = this;
  29616. if (priority === void 0) { priority = 0; }
  29617. if (maximumScale === void 0) { maximumScale = 2; }
  29618. _super.call(this, priority);
  29619. this.priority = priority;
  29620. this.maximumScale = maximumScale;
  29621. this._currentScale = 1;
  29622. this.apply = function (scene) {
  29623. _this._currentScale++;
  29624. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29625. return _this._currentScale >= _this.maximumScale;
  29626. };
  29627. }
  29628. return HardwareScalingOptimization;
  29629. })(SceneOptimization);
  29630. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29631. var ShadowsOptimization = (function (_super) {
  29632. __extends(ShadowsOptimization, _super);
  29633. function ShadowsOptimization() {
  29634. _super.apply(this, arguments);
  29635. this.apply = function (scene) {
  29636. scene.shadowsEnabled = false;
  29637. return true;
  29638. };
  29639. }
  29640. return ShadowsOptimization;
  29641. })(SceneOptimization);
  29642. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29643. var PostProcessesOptimization = (function (_super) {
  29644. __extends(PostProcessesOptimization, _super);
  29645. function PostProcessesOptimization() {
  29646. _super.apply(this, arguments);
  29647. this.apply = function (scene) {
  29648. scene.postProcessesEnabled = false;
  29649. return true;
  29650. };
  29651. }
  29652. return PostProcessesOptimization;
  29653. })(SceneOptimization);
  29654. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29655. var LensFlaresOptimization = (function (_super) {
  29656. __extends(LensFlaresOptimization, _super);
  29657. function LensFlaresOptimization() {
  29658. _super.apply(this, arguments);
  29659. this.apply = function (scene) {
  29660. scene.lensFlaresEnabled = false;
  29661. return true;
  29662. };
  29663. }
  29664. return LensFlaresOptimization;
  29665. })(SceneOptimization);
  29666. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29667. var ParticlesOptimization = (function (_super) {
  29668. __extends(ParticlesOptimization, _super);
  29669. function ParticlesOptimization() {
  29670. _super.apply(this, arguments);
  29671. this.apply = function (scene) {
  29672. scene.particlesEnabled = false;
  29673. return true;
  29674. };
  29675. }
  29676. return ParticlesOptimization;
  29677. })(SceneOptimization);
  29678. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29679. var RenderTargetsOptimization = (function (_super) {
  29680. __extends(RenderTargetsOptimization, _super);
  29681. function RenderTargetsOptimization() {
  29682. _super.apply(this, arguments);
  29683. this.apply = function (scene) {
  29684. scene.renderTargetsEnabled = false;
  29685. return true;
  29686. };
  29687. }
  29688. return RenderTargetsOptimization;
  29689. })(SceneOptimization);
  29690. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29691. var MergeMeshesOptimization = (function (_super) {
  29692. __extends(MergeMeshesOptimization, _super);
  29693. function MergeMeshesOptimization() {
  29694. var _this = this;
  29695. _super.apply(this, arguments);
  29696. this._canBeMerged = function (abstractMesh) {
  29697. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29698. return false;
  29699. }
  29700. var mesh = abstractMesh;
  29701. if (!mesh.isVisible || !mesh.isEnabled()) {
  29702. return false;
  29703. }
  29704. if (mesh.instances.length > 0) {
  29705. return false;
  29706. }
  29707. if (mesh.skeleton || mesh.hasLODLevels) {
  29708. return false;
  29709. }
  29710. return true;
  29711. };
  29712. this.apply = function (scene, updateSelectionTree) {
  29713. var globalPool = scene.meshes.slice(0);
  29714. var globalLength = globalPool.length;
  29715. for (var index = 0; index < globalLength; index++) {
  29716. var currentPool = new Array();
  29717. var current = globalPool[index];
  29718. // Checks
  29719. if (!_this._canBeMerged(current)) {
  29720. continue;
  29721. }
  29722. currentPool.push(current);
  29723. // Find compatible meshes
  29724. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29725. var otherMesh = globalPool[subIndex];
  29726. if (!_this._canBeMerged(otherMesh)) {
  29727. continue;
  29728. }
  29729. if (otherMesh.material !== current.material) {
  29730. continue;
  29731. }
  29732. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29733. continue;
  29734. }
  29735. currentPool.push(otherMesh);
  29736. globalLength--;
  29737. globalPool.splice(subIndex, 1);
  29738. subIndex--;
  29739. }
  29740. if (currentPool.length < 2) {
  29741. continue;
  29742. }
  29743. // Merge meshes
  29744. BABYLON.Mesh.MergeMeshes(currentPool);
  29745. }
  29746. if (updateSelectionTree != undefined) {
  29747. if (updateSelectionTree) {
  29748. scene.createOrUpdateSelectionOctree();
  29749. }
  29750. }
  29751. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29752. scene.createOrUpdateSelectionOctree();
  29753. }
  29754. return true;
  29755. };
  29756. }
  29757. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29758. get: function () {
  29759. return MergeMeshesOptimization._UpdateSelectionTree;
  29760. },
  29761. set: function (value) {
  29762. MergeMeshesOptimization._UpdateSelectionTree = value;
  29763. },
  29764. enumerable: true,
  29765. configurable: true
  29766. });
  29767. MergeMeshesOptimization._UpdateSelectionTree = false;
  29768. return MergeMeshesOptimization;
  29769. })(SceneOptimization);
  29770. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29771. // Options
  29772. var SceneOptimizerOptions = (function () {
  29773. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29774. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29775. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29776. this.targetFrameRate = targetFrameRate;
  29777. this.trackerDuration = trackerDuration;
  29778. this.optimizations = new Array();
  29779. }
  29780. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29781. var result = new SceneOptimizerOptions(targetFrameRate);
  29782. var priority = 0;
  29783. result.optimizations.push(new MergeMeshesOptimization(priority));
  29784. result.optimizations.push(new ShadowsOptimization(priority));
  29785. result.optimizations.push(new LensFlaresOptimization(priority));
  29786. // Next priority
  29787. priority++;
  29788. result.optimizations.push(new PostProcessesOptimization(priority));
  29789. result.optimizations.push(new ParticlesOptimization(priority));
  29790. // Next priority
  29791. priority++;
  29792. result.optimizations.push(new TextureOptimization(priority, 1024));
  29793. return result;
  29794. };
  29795. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29796. var result = new SceneOptimizerOptions(targetFrameRate);
  29797. var priority = 0;
  29798. result.optimizations.push(new MergeMeshesOptimization(priority));
  29799. result.optimizations.push(new ShadowsOptimization(priority));
  29800. result.optimizations.push(new LensFlaresOptimization(priority));
  29801. // Next priority
  29802. priority++;
  29803. result.optimizations.push(new PostProcessesOptimization(priority));
  29804. result.optimizations.push(new ParticlesOptimization(priority));
  29805. // Next priority
  29806. priority++;
  29807. result.optimizations.push(new TextureOptimization(priority, 512));
  29808. // Next priority
  29809. priority++;
  29810. result.optimizations.push(new RenderTargetsOptimization(priority));
  29811. // Next priority
  29812. priority++;
  29813. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29814. return result;
  29815. };
  29816. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29817. var result = new SceneOptimizerOptions(targetFrameRate);
  29818. var priority = 0;
  29819. result.optimizations.push(new MergeMeshesOptimization(priority));
  29820. result.optimizations.push(new ShadowsOptimization(priority));
  29821. result.optimizations.push(new LensFlaresOptimization(priority));
  29822. // Next priority
  29823. priority++;
  29824. result.optimizations.push(new PostProcessesOptimization(priority));
  29825. result.optimizations.push(new ParticlesOptimization(priority));
  29826. // Next priority
  29827. priority++;
  29828. result.optimizations.push(new TextureOptimization(priority, 256));
  29829. // Next priority
  29830. priority++;
  29831. result.optimizations.push(new RenderTargetsOptimization(priority));
  29832. // Next priority
  29833. priority++;
  29834. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29835. return result;
  29836. };
  29837. return SceneOptimizerOptions;
  29838. })();
  29839. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29840. // Scene optimizer tool
  29841. var SceneOptimizer = (function () {
  29842. function SceneOptimizer() {
  29843. }
  29844. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29845. // TODO: add an epsilon
  29846. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29847. if (onSuccess) {
  29848. onSuccess();
  29849. }
  29850. return;
  29851. }
  29852. // Apply current level of optimizations
  29853. var allDone = true;
  29854. var noOptimizationApplied = true;
  29855. for (var index = 0; index < options.optimizations.length; index++) {
  29856. var optimization = options.optimizations[index];
  29857. if (optimization.priority === currentPriorityLevel) {
  29858. noOptimizationApplied = false;
  29859. allDone = allDone && optimization.apply(scene);
  29860. }
  29861. }
  29862. // If no optimization was applied, this is a failure :(
  29863. if (noOptimizationApplied) {
  29864. if (onFailure) {
  29865. onFailure();
  29866. }
  29867. return;
  29868. }
  29869. // If all optimizations were done, move to next level
  29870. if (allDone) {
  29871. currentPriorityLevel++;
  29872. }
  29873. // Let's the system running for a specific amount of time before checking FPS
  29874. scene.executeWhenReady(function () {
  29875. setTimeout(function () {
  29876. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29877. }, options.trackerDuration);
  29878. });
  29879. };
  29880. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29881. if (!options) {
  29882. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29883. }
  29884. // Let's the system running for a specific amount of time before checking FPS
  29885. scene.executeWhenReady(function () {
  29886. setTimeout(function () {
  29887. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29888. }, options.trackerDuration);
  29889. });
  29890. };
  29891. return SceneOptimizer;
  29892. })();
  29893. BABYLON.SceneOptimizer = SceneOptimizer;
  29894. })(BABYLON || (BABYLON = {}));
  29895. var BABYLON;
  29896. (function (BABYLON) {
  29897. var Internals;
  29898. (function (Internals) {
  29899. var MeshLODLevel = (function () {
  29900. function MeshLODLevel(distance, mesh) {
  29901. this.distance = distance;
  29902. this.mesh = mesh;
  29903. }
  29904. return MeshLODLevel;
  29905. })();
  29906. Internals.MeshLODLevel = MeshLODLevel;
  29907. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29908. })(BABYLON || (BABYLON = {}));
  29909. var BABYLON;
  29910. (function (BABYLON) {
  29911. var AudioEngine = (function () {
  29912. function AudioEngine() {
  29913. this._audioContext = null;
  29914. this._audioContextInitialized = false;
  29915. this.canUseWebAudio = false;
  29916. this.WarnedWebAudioUnsupported = false;
  29917. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29918. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29919. this.canUseWebAudio = true;
  29920. }
  29921. }
  29922. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29923. get: function () {
  29924. if (!this._audioContextInitialized) {
  29925. this._initializeAudioContext();
  29926. }
  29927. return this._audioContext;
  29928. },
  29929. enumerable: true,
  29930. configurable: true
  29931. });
  29932. AudioEngine.prototype._initializeAudioContext = function () {
  29933. try {
  29934. if (this.canUseWebAudio) {
  29935. this._audioContext = new AudioContext();
  29936. // create a global volume gain node
  29937. this.masterGain = this._audioContext.createGain();
  29938. this.masterGain.gain.value = 1;
  29939. this.masterGain.connect(this._audioContext.destination);
  29940. this._audioContextInitialized = true;
  29941. }
  29942. }
  29943. catch (e) {
  29944. this.canUseWebAudio = false;
  29945. BABYLON.Tools.Error("Web Audio: " + e.message);
  29946. }
  29947. };
  29948. AudioEngine.prototype.dispose = function () {
  29949. if (this.canUseWebAudio && this._audioContextInitialized) {
  29950. if (this._connectedAnalyser) {
  29951. this._connectedAnalyser.stopDebugCanvas();
  29952. this._connectedAnalyser.dispose();
  29953. this.masterGain.disconnect();
  29954. this.masterGain.connect(this._audioContext.destination);
  29955. this._connectedAnalyser = null;
  29956. }
  29957. this.masterGain.gain.value = 1;
  29958. }
  29959. this.WarnedWebAudioUnsupported = false;
  29960. };
  29961. AudioEngine.prototype.getGlobalVolume = function () {
  29962. if (this.canUseWebAudio && this._audioContextInitialized) {
  29963. return this.masterGain.gain.value;
  29964. }
  29965. else {
  29966. return -1;
  29967. }
  29968. };
  29969. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29970. if (this.canUseWebAudio && this._audioContextInitialized) {
  29971. this.masterGain.gain.value = newVolume;
  29972. }
  29973. };
  29974. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29975. if (this._connectedAnalyser) {
  29976. this._connectedAnalyser.stopDebugCanvas();
  29977. }
  29978. if (this.canUseWebAudio && this._audioContextInitialized) {
  29979. this._connectedAnalyser = analyser;
  29980. this.masterGain.disconnect();
  29981. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29982. }
  29983. };
  29984. return AudioEngine;
  29985. })();
  29986. BABYLON.AudioEngine = AudioEngine;
  29987. })(BABYLON || (BABYLON = {}));
  29988. var BABYLON;
  29989. (function (BABYLON) {
  29990. var Sound = (function () {
  29991. /**
  29992. * Create a sound and attach it to a scene
  29993. * @param name Name of your sound
  29994. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29995. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29996. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29997. */
  29998. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29999. var _this = this;
  30000. this.autoplay = false;
  30001. this.loop = false;
  30002. this.useCustomAttenuation = false;
  30003. this.spatialSound = false;
  30004. this.refDistance = 1;
  30005. this.rolloffFactor = 1;
  30006. this.maxDistance = 100;
  30007. this.distanceModel = "linear";
  30008. this._panningModel = "equalpower";
  30009. this._playbackRate = 1;
  30010. this._startTime = 0;
  30011. this._startOffset = 0;
  30012. this._position = BABYLON.Vector3.Zero();
  30013. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30014. this._volume = 1;
  30015. this._isLoaded = false;
  30016. this._isReadyToPlay = false;
  30017. this.isPlaying = false;
  30018. this.isPaused = false;
  30019. this._isDirectional = false;
  30020. // Used if you'd like to create a directional sound.
  30021. // If not set, the sound will be omnidirectional
  30022. this._coneInnerAngle = 360;
  30023. this._coneOuterAngle = 360;
  30024. this._coneOuterGain = 0;
  30025. this.name = name;
  30026. this._scene = scene;
  30027. this._readyToPlayCallback = readyToPlayCallback;
  30028. // Default custom attenuation function is a linear attenuation
  30029. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30030. if (currentDistance < maxDistance) {
  30031. return currentVolume * (1 - currentDistance / maxDistance);
  30032. }
  30033. else {
  30034. return 0;
  30035. }
  30036. };
  30037. if (options) {
  30038. this.autoplay = options.autoplay || false;
  30039. this.loop = options.loop || false;
  30040. // if volume === 0, we need another way to check this option
  30041. if (options.volume !== undefined) {
  30042. this._volume = options.volume;
  30043. }
  30044. this.spatialSound = options.spatialSound || false;
  30045. this.maxDistance = options.maxDistance || 100;
  30046. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30047. this.rolloffFactor = options.rolloffFactor || 1;
  30048. this.refDistance = options.refDistance || 1;
  30049. this.distanceModel = options.distanceModel || "linear";
  30050. this._playbackRate = options.playbackRate || 1;
  30051. }
  30052. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30053. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30054. this._soundGain.gain.value = this._volume;
  30055. this._inputAudioNode = this._soundGain;
  30056. this._ouputAudioNode = this._soundGain;
  30057. if (this.spatialSound) {
  30058. this._createSpatialParameters();
  30059. }
  30060. this._scene.mainSoundTrack.AddSound(this);
  30061. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30062. if (urlOrArrayBuffer) {
  30063. // If it's an URL
  30064. if (typeof (urlOrArrayBuffer) === "string") {
  30065. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30066. }
  30067. else {
  30068. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30069. this._soundLoaded(urlOrArrayBuffer);
  30070. }
  30071. else {
  30072. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30073. }
  30074. }
  30075. }
  30076. }
  30077. else {
  30078. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30079. this._scene.mainSoundTrack.AddSound(this);
  30080. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30081. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30082. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30083. }
  30084. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30085. if (this._readyToPlayCallback) {
  30086. window.setTimeout(function () {
  30087. _this._readyToPlayCallback();
  30088. }, 1000);
  30089. }
  30090. }
  30091. }
  30092. Sound.prototype.dispose = function () {
  30093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30094. if (this.isPlaying) {
  30095. this.stop();
  30096. }
  30097. this._isReadyToPlay = false;
  30098. if (this.soundTrackId === -1) {
  30099. this._scene.mainSoundTrack.RemoveSound(this);
  30100. }
  30101. else {
  30102. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30103. }
  30104. if (this._soundGain) {
  30105. this._soundGain.disconnect();
  30106. this._soundGain = null;
  30107. }
  30108. if (this._soundPanner) {
  30109. this._soundPanner.disconnect();
  30110. this._soundPanner = null;
  30111. }
  30112. if (this._soundSource) {
  30113. this._soundSource.disconnect();
  30114. this._soundSource = null;
  30115. }
  30116. this._audioBuffer = null;
  30117. if (this._connectedMesh) {
  30118. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30119. this._connectedMesh = null;
  30120. }
  30121. }
  30122. };
  30123. Sound.prototype._soundLoaded = function (audioData) {
  30124. var _this = this;
  30125. this._isLoaded = true;
  30126. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30127. _this._audioBuffer = buffer;
  30128. _this._isReadyToPlay = true;
  30129. if (_this.autoplay) {
  30130. _this.play();
  30131. }
  30132. if (_this._readyToPlayCallback) {
  30133. _this._readyToPlayCallback();
  30134. }
  30135. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30136. };
  30137. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30138. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30139. this._audioBuffer = audioBuffer;
  30140. this._isReadyToPlay = true;
  30141. }
  30142. };
  30143. Sound.prototype.updateOptions = function (options) {
  30144. if (options) {
  30145. this.loop = options.loop || this.loop;
  30146. this.maxDistance = options.maxDistance || this.maxDistance;
  30147. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30148. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30149. this.refDistance = options.refDistance || this.refDistance;
  30150. this.distanceModel = options.distanceModel || this.distanceModel;
  30151. this._playbackRate = options.playbackRate || this._playbackRate;
  30152. this._updateSpatialParameters();
  30153. if (this.isPlaying) {
  30154. this._soundSource.playbackRate.value = this._playbackRate;
  30155. }
  30156. }
  30157. };
  30158. Sound.prototype._createSpatialParameters = function () {
  30159. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30160. if (this._scene.headphone) {
  30161. this._panningModel = "HRTF";
  30162. }
  30163. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30164. this._updateSpatialParameters();
  30165. this._soundPanner.connect(this._ouputAudioNode);
  30166. this._inputAudioNode = this._soundPanner;
  30167. }
  30168. };
  30169. Sound.prototype._updateSpatialParameters = function () {
  30170. if (this.spatialSound) {
  30171. if (this.useCustomAttenuation) {
  30172. // Tricks to disable in a way embedded Web Audio attenuation
  30173. this._soundPanner.distanceModel = "linear";
  30174. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30175. this._soundPanner.refDistance = 1;
  30176. this._soundPanner.rolloffFactor = 1;
  30177. this._soundPanner.panningModel = this._panningModel;
  30178. }
  30179. else {
  30180. this._soundPanner.distanceModel = this.distanceModel;
  30181. this._soundPanner.maxDistance = this.maxDistance;
  30182. this._soundPanner.refDistance = this.refDistance;
  30183. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30184. this._soundPanner.panningModel = this._panningModel;
  30185. }
  30186. }
  30187. };
  30188. Sound.prototype.switchPanningModelToHRTF = function () {
  30189. this._panningModel = "HRTF";
  30190. this._switchPanningModel();
  30191. };
  30192. Sound.prototype.switchPanningModelToEqualPower = function () {
  30193. this._panningModel = "equalpower";
  30194. this._switchPanningModel();
  30195. };
  30196. Sound.prototype._switchPanningModel = function () {
  30197. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30198. this._soundPanner.panningModel = this._panningModel;
  30199. }
  30200. };
  30201. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30202. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30203. this._ouputAudioNode.disconnect();
  30204. this._ouputAudioNode.connect(soundTrackAudioNode);
  30205. }
  30206. };
  30207. /**
  30208. * Transform this sound into a directional source
  30209. * @param coneInnerAngle Size of the inner cone in degree
  30210. * @param coneOuterAngle Size of the outer cone in degree
  30211. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30212. */
  30213. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30214. if (coneOuterAngle < coneInnerAngle) {
  30215. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30216. return;
  30217. }
  30218. this._coneInnerAngle = coneInnerAngle;
  30219. this._coneOuterAngle = coneOuterAngle;
  30220. this._coneOuterGain = coneOuterGain;
  30221. this._isDirectional = true;
  30222. if (this.isPlaying && this.loop) {
  30223. this.stop();
  30224. this.play();
  30225. }
  30226. };
  30227. Sound.prototype.setPosition = function (newPosition) {
  30228. this._position = newPosition;
  30229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30230. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30231. }
  30232. };
  30233. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30234. this._localDirection = newLocalDirection;
  30235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30236. this._updateDirection();
  30237. }
  30238. };
  30239. Sound.prototype._updateDirection = function () {
  30240. var mat = this._connectedMesh.getWorldMatrix();
  30241. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30242. direction.normalize();
  30243. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30244. };
  30245. Sound.prototype.updateDistanceFromListener = function () {
  30246. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30247. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30248. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30249. }
  30250. };
  30251. Sound.prototype.setAttenuationFunction = function (callback) {
  30252. this._customAttenuationFunction = callback;
  30253. };
  30254. /**
  30255. * Play the sound
  30256. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30257. */
  30258. Sound.prototype.play = function (time) {
  30259. var _this = this;
  30260. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30261. try {
  30262. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30263. if (!this._soundSource) {
  30264. if (this.spatialSound) {
  30265. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30266. if (this._isDirectional) {
  30267. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30268. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30269. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30270. if (this._connectedMesh) {
  30271. this._updateDirection();
  30272. }
  30273. else {
  30274. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30275. }
  30276. }
  30277. }
  30278. }
  30279. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30280. this._soundSource.buffer = this._audioBuffer;
  30281. this._soundSource.connect(this._inputAudioNode);
  30282. this._soundSource.loop = this.loop;
  30283. this._soundSource.playbackRate.value = this._playbackRate;
  30284. this._startTime = startTime;
  30285. this._soundSource.onended = function () { _this._onended(); };
  30286. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30287. this.isPlaying = true;
  30288. this.isPaused = false;
  30289. }
  30290. catch (ex) {
  30291. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30292. }
  30293. }
  30294. };
  30295. Sound.prototype._onended = function () {
  30296. this.isPlaying = false;
  30297. if (this.onended) {
  30298. this.onended();
  30299. }
  30300. };
  30301. /**
  30302. * Stop the sound
  30303. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30304. */
  30305. Sound.prototype.stop = function (time) {
  30306. if (this.isPlaying) {
  30307. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30308. this._soundSource.stop(stopTime);
  30309. this.isPlaying = false;
  30310. }
  30311. };
  30312. Sound.prototype.pause = function () {
  30313. if (this.isPlaying) {
  30314. this.stop(0);
  30315. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30316. this.isPaused = true;
  30317. }
  30318. };
  30319. Sound.prototype.setVolume = function (newVolume, time) {
  30320. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30321. if (time) {
  30322. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30323. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30324. }
  30325. else {
  30326. this._soundGain.gain.value = newVolume;
  30327. }
  30328. }
  30329. this._volume = newVolume;
  30330. };
  30331. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30332. this._playbackRate = newPlaybackRate;
  30333. if (this.isPlaying) {
  30334. this._soundSource.playbackRate.value = this._playbackRate;
  30335. }
  30336. };
  30337. Sound.prototype.getVolume = function () {
  30338. return this._volume;
  30339. };
  30340. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30341. var _this = this;
  30342. this._connectedMesh = meshToConnectTo;
  30343. if (!this.spatialSound) {
  30344. this.spatialSound = true;
  30345. this._createSpatialParameters();
  30346. if (this.isPlaying && this.loop) {
  30347. this.stop();
  30348. this.play();
  30349. }
  30350. }
  30351. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30352. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30353. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30354. };
  30355. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30356. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30358. this._updateDirection();
  30359. }
  30360. };
  30361. return Sound;
  30362. })();
  30363. BABYLON.Sound = Sound;
  30364. })(BABYLON || (BABYLON = {}));
  30365. var BABYLON;
  30366. (function (BABYLON) {
  30367. var SoundTrack = (function () {
  30368. function SoundTrack(scene, options) {
  30369. this.id = -1;
  30370. this._isMainTrack = false;
  30371. this._scene = scene;
  30372. this._audioEngine = BABYLON.Engine.audioEngine;
  30373. this.soundCollection = new Array();
  30374. if (this._audioEngine.canUseWebAudio) {
  30375. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30376. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30377. if (options) {
  30378. if (options.volume) {
  30379. this._outputAudioNode.gain.value = options.volume;
  30380. }
  30381. if (options.mainTrack) {
  30382. this._isMainTrack = options.mainTrack;
  30383. }
  30384. }
  30385. }
  30386. if (!this._isMainTrack) {
  30387. this._scene.soundTracks.push(this);
  30388. this.id = this._scene.soundTracks.length - 1;
  30389. }
  30390. }
  30391. SoundTrack.prototype.dispose = function () {
  30392. if (this._audioEngine.canUseWebAudio) {
  30393. if (this._connectedAnalyser) {
  30394. this._connectedAnalyser.stopDebugCanvas();
  30395. }
  30396. while (this.soundCollection.length) {
  30397. this.soundCollection[0].dispose();
  30398. }
  30399. if (this._outputAudioNode) {
  30400. this._outputAudioNode.disconnect();
  30401. }
  30402. this._outputAudioNode = null;
  30403. }
  30404. };
  30405. SoundTrack.prototype.AddSound = function (sound) {
  30406. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30407. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30408. }
  30409. if (sound.soundTrackId) {
  30410. if (sound.soundTrackId === -1) {
  30411. this._scene.mainSoundTrack.RemoveSound(sound);
  30412. }
  30413. else {
  30414. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30415. }
  30416. }
  30417. this.soundCollection.push(sound);
  30418. sound.soundTrackId = this.id;
  30419. };
  30420. SoundTrack.prototype.RemoveSound = function (sound) {
  30421. var index = this.soundCollection.indexOf(sound);
  30422. if (index !== -1) {
  30423. this.soundCollection.splice(index, 1);
  30424. }
  30425. };
  30426. SoundTrack.prototype.setVolume = function (newVolume) {
  30427. if (this._audioEngine.canUseWebAudio) {
  30428. this._outputAudioNode.gain.value = newVolume;
  30429. }
  30430. };
  30431. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30432. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30433. for (var i = 0; i < this.soundCollection.length; i++) {
  30434. this.soundCollection[i].switchPanningModelToHRTF();
  30435. }
  30436. }
  30437. };
  30438. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30439. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30440. for (var i = 0; i < this.soundCollection.length; i++) {
  30441. this.soundCollection[i].switchPanningModelToEqualPower();
  30442. }
  30443. }
  30444. };
  30445. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30446. if (this._connectedAnalyser) {
  30447. this._connectedAnalyser.stopDebugCanvas();
  30448. }
  30449. this._connectedAnalyser = analyser;
  30450. if (this._audioEngine.canUseWebAudio) {
  30451. this._outputAudioNode.disconnect();
  30452. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30453. }
  30454. };
  30455. return SoundTrack;
  30456. })();
  30457. BABYLON.SoundTrack = SoundTrack;
  30458. })(BABYLON || (BABYLON = {}));
  30459. var BABYLON;
  30460. (function (BABYLON) {
  30461. var DebugLayer = (function () {
  30462. function DebugLayer(scene) {
  30463. var _this = this;
  30464. this._transformationMatrix = BABYLON.Matrix.Identity();
  30465. this._enabled = false;
  30466. this._labelsEnabled = false;
  30467. this._displayStatistics = true;
  30468. this._displayTree = false;
  30469. this._displayLogs = false;
  30470. this._identityMatrix = BABYLON.Matrix.Identity();
  30471. this.axisRatio = 0.02;
  30472. this.accentColor = "orange";
  30473. this._scene = scene;
  30474. this._syncPositions = function () {
  30475. var engine = _this._scene.getEngine();
  30476. var canvasRect = engine.getRenderingCanvasClientRect();
  30477. if (_this._showUI) {
  30478. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30479. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30480. _this._statsDiv.style.width = "400px";
  30481. _this._statsDiv.style.height = "auto";
  30482. _this._statsSubsetDiv.style.maxHeight = "240px";
  30483. _this._optionsDiv.style.left = "0px";
  30484. _this._optionsDiv.style.top = "10px";
  30485. _this._optionsDiv.style.width = "200px";
  30486. _this._optionsDiv.style.height = "auto";
  30487. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30488. _this._logDiv.style.left = "0px";
  30489. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30490. _this._logDiv.style.width = "600px";
  30491. _this._logDiv.style.height = "160px";
  30492. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30493. _this._treeDiv.style.top = "10px";
  30494. _this._treeDiv.style.width = "300px";
  30495. _this._treeDiv.style.height = "auto";
  30496. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30497. }
  30498. _this._globalDiv.style.left = canvasRect.left + "px";
  30499. _this._globalDiv.style.top = canvasRect.top + "px";
  30500. _this._drawingCanvas.style.left = "0px";
  30501. _this._drawingCanvas.style.top = "0px";
  30502. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30503. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30504. var devicePixelRatio = window.devicePixelRatio || 1;
  30505. var context = _this._drawingContext;
  30506. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30507. context.mozBackingStorePixelRatio ||
  30508. context.msBackingStorePixelRatio ||
  30509. context.oBackingStorePixelRatio ||
  30510. context.backingStorePixelRatio || 1;
  30511. _this._ratio = devicePixelRatio / backingStoreRatio;
  30512. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30513. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30514. };
  30515. this._onCanvasClick = function (evt) {
  30516. _this._clickPosition = {
  30517. x: evt.clientX * _this._ratio,
  30518. y: evt.clientY * _this._ratio
  30519. };
  30520. };
  30521. this._syncUI = function () {
  30522. if (_this._showUI) {
  30523. if (_this._displayStatistics) {
  30524. _this._displayStats();
  30525. _this._statsDiv.style.display = "";
  30526. }
  30527. else {
  30528. _this._statsDiv.style.display = "none";
  30529. }
  30530. if (_this._displayLogs) {
  30531. _this._logDiv.style.display = "";
  30532. }
  30533. else {
  30534. _this._logDiv.style.display = "none";
  30535. }
  30536. if (_this._displayTree) {
  30537. _this._treeDiv.style.display = "";
  30538. if (_this._needToRefreshMeshesTree) {
  30539. _this._needToRefreshMeshesTree = false;
  30540. _this._refreshMeshesTreeContent();
  30541. }
  30542. }
  30543. else {
  30544. _this._treeDiv.style.display = "none";
  30545. }
  30546. }
  30547. };
  30548. this._syncData = function () {
  30549. if (_this._labelsEnabled || !_this._showUI) {
  30550. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30551. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30552. var engine = _this._scene.getEngine();
  30553. var viewport = _this._camera.viewport;
  30554. var globalViewport = viewport.toGlobal(engine);
  30555. // Meshes
  30556. var meshes = _this._camera.getActiveMeshes();
  30557. for (var index = 0; index < meshes.length; index++) {
  30558. var mesh = meshes.data[index];
  30559. var position = mesh.getBoundingInfo().boundingSphere.center;
  30560. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30561. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30562. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30563. }
  30564. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30565. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30566. }
  30567. }
  30568. // Cameras
  30569. var cameras = _this._scene.cameras;
  30570. for (index = 0; index < cameras.length; index++) {
  30571. var camera = cameras[index];
  30572. if (camera === _this._camera) {
  30573. continue;
  30574. }
  30575. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30576. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30577. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30578. _this._camera.detachControl(engine.getRenderingCanvas());
  30579. _this._camera = camera;
  30580. _this._camera.attachControl(engine.getRenderingCanvas());
  30581. }, function () { return "purple"; });
  30582. }
  30583. }
  30584. // Lights
  30585. var lights = _this._scene.lights;
  30586. for (index = 0; index < lights.length; index++) {
  30587. var light = lights[index];
  30588. if (light.position) {
  30589. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30590. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30591. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30592. light.setEnabled(!light.isEnabled());
  30593. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30594. }
  30595. }
  30596. }
  30597. }
  30598. _this._clickPosition = undefined;
  30599. };
  30600. }
  30601. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30602. while (this._treeSubsetDiv.hasChildNodes()) {
  30603. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30604. }
  30605. // Add meshes
  30606. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30607. sortedArray.sort(function (a, b) {
  30608. if (a.name === b.name) {
  30609. return 0;
  30610. }
  30611. return (a.name > b.name) ? 1 : -1;
  30612. });
  30613. for (var index = 0; index < sortedArray.length; index++) {
  30614. var mesh = sortedArray[index];
  30615. if (!mesh.isEnabled()) {
  30616. continue;
  30617. }
  30618. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30619. m.isVisible = element.checked;
  30620. }, mesh);
  30621. }
  30622. };
  30623. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30624. this._drawingContext.beginPath();
  30625. this._drawingContext.moveTo(zero.x, zero.y);
  30626. this._drawingContext.lineTo(unit.x, unit.y);
  30627. this._drawingContext.strokeStyle = color;
  30628. this._drawingContext.lineWidth = 4;
  30629. this._drawingContext.stroke();
  30630. this._drawingContext.font = "normal 14px Segoe UI";
  30631. this._drawingContext.fillStyle = color;
  30632. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30633. };
  30634. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30635. var position = mesh.getBoundingInfo().boundingSphere.center;
  30636. var worldMatrix = mesh.getWorldMatrix();
  30637. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30638. var unit = (unprojectedVector.subtract(position)).length();
  30639. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30640. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30641. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30642. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30643. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30644. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30645. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30646. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30647. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30648. };
  30649. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30650. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30651. this._drawingContext.font = "normal 12px Segoe UI";
  30652. var textMetrics = this._drawingContext.measureText(text);
  30653. var centerX = projectedPosition.x - textMetrics.width / 2;
  30654. var centerY = projectedPosition.y;
  30655. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30656. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30657. onClick();
  30658. }
  30659. this._drawingContext.beginPath();
  30660. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30661. this._drawingContext.fillStyle = getFillStyle();
  30662. this._drawingContext.globalAlpha = 0.5;
  30663. this._drawingContext.fill();
  30664. this._drawingContext.globalAlpha = 1.0;
  30665. this._drawingContext.strokeStyle = '#FFFFFF';
  30666. this._drawingContext.lineWidth = 1;
  30667. this._drawingContext.stroke();
  30668. this._drawingContext.fillStyle = "#FFFFFF";
  30669. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30670. this._drawingContext.beginPath();
  30671. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30672. this._drawingContext.fill();
  30673. }
  30674. };
  30675. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30676. if (!this._clickPosition) {
  30677. return false;
  30678. }
  30679. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30680. return false;
  30681. }
  30682. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30683. return false;
  30684. }
  30685. return true;
  30686. };
  30687. DebugLayer.prototype.isVisible = function () {
  30688. return this._enabled;
  30689. };
  30690. DebugLayer.prototype.hide = function () {
  30691. if (!this._enabled) {
  30692. return;
  30693. }
  30694. this._enabled = false;
  30695. var engine = this._scene.getEngine();
  30696. this._scene.unregisterBeforeRender(this._syncData);
  30697. this._scene.unregisterAfterRender(this._syncUI);
  30698. document.body.removeChild(this._globalDiv);
  30699. window.removeEventListener("resize", this._syncPositions);
  30700. this._scene.forceShowBoundingBoxes = false;
  30701. this._scene.forceWireframe = false;
  30702. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30703. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30704. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30705. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30706. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30707. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30708. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30709. this._scene.shadowsEnabled = true;
  30710. this._scene.particlesEnabled = true;
  30711. this._scene.postProcessesEnabled = true;
  30712. this._scene.collisionsEnabled = true;
  30713. this._scene.lightsEnabled = true;
  30714. this._scene.texturesEnabled = true;
  30715. this._scene.lensFlaresEnabled = true;
  30716. this._scene.proceduralTexturesEnabled = true;
  30717. this._scene.renderTargetsEnabled = true;
  30718. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30719. };
  30720. DebugLayer.prototype.show = function (showUI, camera) {
  30721. if (showUI === void 0) { showUI = true; }
  30722. if (camera === void 0) { camera = null; }
  30723. if (this._enabled) {
  30724. return;
  30725. }
  30726. this._enabled = true;
  30727. if (camera) {
  30728. this._camera = camera;
  30729. }
  30730. else {
  30731. this._camera = this._scene.activeCamera;
  30732. }
  30733. this._showUI = showUI;
  30734. var engine = this._scene.getEngine();
  30735. this._globalDiv = document.createElement("div");
  30736. document.body.appendChild(this._globalDiv);
  30737. this._generateDOMelements();
  30738. window.addEventListener("resize", this._syncPositions);
  30739. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30740. this._syncPositions();
  30741. this._scene.registerBeforeRender(this._syncData);
  30742. this._scene.registerAfterRender(this._syncUI);
  30743. };
  30744. DebugLayer.prototype._clearLabels = function () {
  30745. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30746. for (var index = 0; index < this._scene.meshes.length; index++) {
  30747. var mesh = this._scene.meshes[index];
  30748. mesh.renderOverlay = false;
  30749. }
  30750. };
  30751. DebugLayer.prototype._generateheader = function (root, text) {
  30752. var header = document.createElement("div");
  30753. header.innerHTML = text + "&nbsp;";
  30754. header.style.textAlign = "right";
  30755. header.style.width = "100%";
  30756. header.style.color = "white";
  30757. header.style.backgroundColor = "Black";
  30758. header.style.padding = "5px 5px 4px 0px";
  30759. header.style.marginLeft = "-5px";
  30760. header.style.fontWeight = "bold";
  30761. root.appendChild(header);
  30762. };
  30763. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30764. var label = document.createElement("label");
  30765. label.innerHTML = title;
  30766. label.style.color = color;
  30767. root.appendChild(label);
  30768. root.appendChild(document.createElement("br"));
  30769. };
  30770. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30771. if (tag === void 0) { tag = null; }
  30772. var label = document.createElement("label");
  30773. var boundingBoxesCheckbox = document.createElement("input");
  30774. boundingBoxesCheckbox.type = "checkbox";
  30775. boundingBoxesCheckbox.checked = initialState;
  30776. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30777. task(evt.target, tag);
  30778. });
  30779. label.appendChild(boundingBoxesCheckbox);
  30780. var container = document.createElement("span");
  30781. var leftPart = document.createElement("span");
  30782. var rightPart = document.createElement("span");
  30783. rightPart.style.cssFloat = "right";
  30784. leftPart.innerHTML = leftTitle;
  30785. rightPart.innerHTML = rightTitle;
  30786. rightPart.style.fontSize = "12px";
  30787. rightPart.style.maxWidth = "200px";
  30788. container.appendChild(leftPart);
  30789. container.appendChild(rightPart);
  30790. label.appendChild(container);
  30791. root.appendChild(label);
  30792. root.appendChild(document.createElement("br"));
  30793. };
  30794. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30795. if (tag === void 0) { tag = null; }
  30796. var label = document.createElement("label");
  30797. var checkBox = document.createElement("input");
  30798. checkBox.type = "checkbox";
  30799. checkBox.checked = initialState;
  30800. checkBox.addEventListener("change", function (evt) {
  30801. task(evt.target, tag);
  30802. });
  30803. label.appendChild(checkBox);
  30804. label.appendChild(document.createTextNode(title));
  30805. root.appendChild(label);
  30806. root.appendChild(document.createElement("br"));
  30807. };
  30808. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30809. if (tag === void 0) { tag = null; }
  30810. var button = document.createElement("button");
  30811. button.innerHTML = title;
  30812. button.style.height = "24px";
  30813. button.style.color = "#444444";
  30814. button.style.border = "1px solid white";
  30815. button.className = "debugLayerButton";
  30816. button.addEventListener("click", function (evt) {
  30817. task(evt.target, tag);
  30818. });
  30819. root.appendChild(button);
  30820. root.appendChild(document.createElement("br"));
  30821. };
  30822. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30823. if (tag === void 0) { tag = null; }
  30824. var label = document.createElement("label");
  30825. var boundingBoxesRadio = document.createElement("input");
  30826. boundingBoxesRadio.type = "radio";
  30827. boundingBoxesRadio.name = name;
  30828. boundingBoxesRadio.checked = initialState;
  30829. boundingBoxesRadio.addEventListener("change", function (evt) {
  30830. task(evt.target, tag);
  30831. });
  30832. label.appendChild(boundingBoxesRadio);
  30833. label.appendChild(document.createTextNode(title));
  30834. root.appendChild(label);
  30835. root.appendChild(document.createElement("br"));
  30836. };
  30837. DebugLayer.prototype._generateDOMelements = function () {
  30838. var _this = this;
  30839. this._globalDiv.id = "DebugLayer";
  30840. this._globalDiv.style.position = "absolute";
  30841. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30842. this._globalDiv.style.fontSize = "14px";
  30843. this._globalDiv.style.color = "white";
  30844. // Drawing canvas
  30845. this._drawingCanvas = document.createElement("canvas");
  30846. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30847. this._drawingCanvas.style.position = "absolute";
  30848. this._drawingCanvas.style.pointerEvents = "none";
  30849. this._drawingContext = this._drawingCanvas.getContext("2d");
  30850. this._globalDiv.appendChild(this._drawingCanvas);
  30851. if (this._showUI) {
  30852. var background = "rgba(128, 128, 128, 0.4)";
  30853. var border = "rgb(180, 180, 180) solid 1px";
  30854. // Stats
  30855. this._statsDiv = document.createElement("div");
  30856. this._statsDiv.id = "DebugLayerStats";
  30857. this._statsDiv.style.border = border;
  30858. this._statsDiv.style.position = "absolute";
  30859. this._statsDiv.style.background = background;
  30860. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30861. this._generateheader(this._statsDiv, "STATISTICS");
  30862. this._statsSubsetDiv = document.createElement("div");
  30863. this._statsSubsetDiv.style.paddingTop = "5px";
  30864. this._statsSubsetDiv.style.paddingBottom = "5px";
  30865. this._statsSubsetDiv.style.overflowY = "auto";
  30866. this._statsDiv.appendChild(this._statsSubsetDiv);
  30867. // Tree
  30868. this._treeDiv = document.createElement("div");
  30869. this._treeDiv.id = "DebugLayerTree";
  30870. this._treeDiv.style.border = border;
  30871. this._treeDiv.style.position = "absolute";
  30872. this._treeDiv.style.background = background;
  30873. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30874. this._treeDiv.style.display = "none";
  30875. this._generateheader(this._treeDiv, "MESHES TREE");
  30876. this._treeSubsetDiv = document.createElement("div");
  30877. this._treeSubsetDiv.style.paddingTop = "5px";
  30878. this._treeSubsetDiv.style.paddingRight = "5px";
  30879. this._treeSubsetDiv.style.overflowY = "auto";
  30880. this._treeSubsetDiv.style.maxHeight = "300px";
  30881. this._treeDiv.appendChild(this._treeSubsetDiv);
  30882. this._needToRefreshMeshesTree = true;
  30883. // Logs
  30884. this._logDiv = document.createElement("div");
  30885. this._logDiv.style.border = border;
  30886. this._logDiv.id = "DebugLayerLogs";
  30887. this._logDiv.style.position = "absolute";
  30888. this._logDiv.style.background = background;
  30889. this._logDiv.style.padding = "0px 0px 0px 5px";
  30890. this._logDiv.style.display = "none";
  30891. this._generateheader(this._logDiv, "LOGS");
  30892. this._logSubsetDiv = document.createElement("div");
  30893. this._logSubsetDiv.style.height = "127px";
  30894. this._logSubsetDiv.style.paddingTop = "5px";
  30895. this._logSubsetDiv.style.overflowY = "auto";
  30896. this._logSubsetDiv.style.fontSize = "12px";
  30897. this._logSubsetDiv.style.fontFamily = "consolas";
  30898. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30899. this._logDiv.appendChild(this._logSubsetDiv);
  30900. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30901. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30902. };
  30903. // Options
  30904. this._optionsDiv = document.createElement("div");
  30905. this._optionsDiv.id = "DebugLayerOptions";
  30906. this._optionsDiv.style.border = border;
  30907. this._optionsDiv.style.position = "absolute";
  30908. this._optionsDiv.style.background = background;
  30909. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30910. this._optionsDiv.style.overflowY = "auto";
  30911. this._generateheader(this._optionsDiv, "OPTIONS");
  30912. this._optionsSubsetDiv = document.createElement("div");
  30913. this._optionsSubsetDiv.style.paddingTop = "5px";
  30914. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30915. this._optionsSubsetDiv.style.overflowY = "auto";
  30916. this._optionsSubsetDiv.style.maxHeight = "200px";
  30917. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30918. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30919. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30920. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30921. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30922. _this._displayTree = element.checked;
  30923. _this._needToRefreshMeshesTree = true;
  30924. });
  30925. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30926. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30927. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30928. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30929. _this._labelsEnabled = element.checked;
  30930. if (!_this._labelsEnabled) {
  30931. _this._clearLabels();
  30932. }
  30933. });
  30934. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  30935. if (element.checked) {
  30936. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  30937. }
  30938. else {
  30939. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  30940. }
  30941. });
  30942. ;
  30943. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30944. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  30945. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  30946. if (element.checked) {
  30947. _this._scene.forceWireframe = false;
  30948. _this._scene.forcePointsCloud = false;
  30949. }
  30950. });
  30951. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  30952. if (element.checked) {
  30953. _this._scene.forceWireframe = true;
  30954. _this._scene.forcePointsCloud = false;
  30955. }
  30956. });
  30957. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  30958. if (element.checked) {
  30959. _this._scene.forceWireframe = false;
  30960. _this._scene.forcePointsCloud = true;
  30961. }
  30962. });
  30963. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30964. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  30965. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  30966. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  30967. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  30968. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  30969. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  30970. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  30971. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  30972. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  30973. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30974. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  30975. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  30976. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  30977. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  30978. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  30979. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  30980. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  30981. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  30982. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  30983. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  30984. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  30985. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  30986. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  30987. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  30988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30989. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30990. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30991. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30992. if (element.checked) {
  30993. _this._scene.headphone = true;
  30994. }
  30995. });
  30996. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30997. if (element.checked) {
  30998. _this._scene.headphone = false;
  30999. }
  31000. });
  31001. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31002. _this._scene.audioEnabled = !element.checked;
  31003. });
  31004. }
  31005. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31006. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31007. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31008. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31009. this._globalDiv.appendChild(this._statsDiv);
  31010. this._globalDiv.appendChild(this._logDiv);
  31011. this._globalDiv.appendChild(this._optionsDiv);
  31012. this._globalDiv.appendChild(this._treeDiv);
  31013. }
  31014. };
  31015. DebugLayer.prototype._displayStats = function () {
  31016. var scene = this._scene;
  31017. var engine = scene.getEngine();
  31018. var glInfo = engine.getGlInfo();
  31019. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31020. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31021. + "<b>Count</b><br>"
  31022. + "Total meshes: " + scene.meshes.length + "<br>"
  31023. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31024. + "Total materials: " + scene.materials.length + "<br>"
  31025. + "Total textures: " + scene.textures.length + "<br>"
  31026. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31027. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31028. + "Active bones: " + scene.getActiveBones() + "<br>"
  31029. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31030. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31031. + "<b>Duration</b><br>"
  31032. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31033. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31034. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31035. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31036. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31037. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31038. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31039. + "</div>"
  31040. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31041. + "<b>Extensions</b><br>"
  31042. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31043. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31044. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31045. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31046. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31047. + "<b>Caps.</b><br>"
  31048. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31049. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31050. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31051. + "</div><br>"
  31052. + "<b>Info</b><br>"
  31053. + glInfo.version + "<br>"
  31054. + glInfo.renderer + "<br>";
  31055. if (this.customStatsFunction) {
  31056. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31057. }
  31058. };
  31059. return DebugLayer;
  31060. })();
  31061. BABYLON.DebugLayer = DebugLayer;
  31062. })(BABYLON || (BABYLON = {}));
  31063. var BABYLON;
  31064. (function (BABYLON) {
  31065. var RawTexture = (function (_super) {
  31066. __extends(RawTexture, _super);
  31067. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31068. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31069. if (invertY === void 0) { invertY = false; }
  31070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31071. _super.call(this, null, scene, !generateMipMaps, invertY);
  31072. this.format = format;
  31073. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31074. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31075. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31076. }
  31077. RawTexture.prototype.update = function (data) {
  31078. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31079. };
  31080. // Statics
  31081. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31082. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31083. if (invertY === void 0) { invertY = false; }
  31084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31085. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31086. };
  31087. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31088. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31089. if (invertY === void 0) { invertY = false; }
  31090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31091. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31092. };
  31093. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31095. if (invertY === void 0) { invertY = false; }
  31096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31097. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31098. };
  31099. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31100. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31101. if (invertY === void 0) { invertY = false; }
  31102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31103. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31104. };
  31105. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31106. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31107. if (invertY === void 0) { invertY = false; }
  31108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31109. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31110. };
  31111. return RawTexture;
  31112. })(BABYLON.Texture);
  31113. BABYLON.RawTexture = RawTexture;
  31114. })(BABYLON || (BABYLON = {}));
  31115. var BABYLON;
  31116. (function (BABYLON) {
  31117. var IndexedVector2 = (function (_super) {
  31118. __extends(IndexedVector2, _super);
  31119. function IndexedVector2(original, index) {
  31120. _super.call(this, original.x, original.y);
  31121. this.index = index;
  31122. }
  31123. return IndexedVector2;
  31124. })(BABYLON.Vector2);
  31125. var PolygonPoints = (function () {
  31126. function PolygonPoints() {
  31127. this.elements = new Array();
  31128. }
  31129. PolygonPoints.prototype.add = function (originalPoints) {
  31130. var _this = this;
  31131. var result = new Array();
  31132. originalPoints.forEach(function (point) {
  31133. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31134. var newPoint = new IndexedVector2(point, _this.elements.length);
  31135. result.push(newPoint);
  31136. _this.elements.push(newPoint);
  31137. }
  31138. });
  31139. return result;
  31140. };
  31141. PolygonPoints.prototype.computeBounds = function () {
  31142. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31143. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31144. this.elements.forEach(function (point) {
  31145. // x
  31146. if (point.x < lmin.x) {
  31147. lmin.x = point.x;
  31148. }
  31149. else if (point.x > lmax.x) {
  31150. lmax.x = point.x;
  31151. }
  31152. // y
  31153. if (point.y < lmin.y) {
  31154. lmin.y = point.y;
  31155. }
  31156. else if (point.y > lmax.y) {
  31157. lmax.y = point.y;
  31158. }
  31159. });
  31160. return {
  31161. min: lmin,
  31162. max: lmax,
  31163. width: lmax.x - lmin.x,
  31164. height: lmax.y - lmin.y
  31165. };
  31166. };
  31167. return PolygonPoints;
  31168. })();
  31169. var Polygon = (function () {
  31170. function Polygon() {
  31171. }
  31172. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31173. return [
  31174. new BABYLON.Vector2(xmin, ymin),
  31175. new BABYLON.Vector2(xmax, ymin),
  31176. new BABYLON.Vector2(xmax, ymax),
  31177. new BABYLON.Vector2(xmin, ymax)
  31178. ];
  31179. };
  31180. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31181. if (cx === void 0) { cx = 0; }
  31182. if (cy === void 0) { cy = 0; }
  31183. if (numberOfSides === void 0) { numberOfSides = 32; }
  31184. var result = new Array();
  31185. var angle = 0;
  31186. var increment = (Math.PI * 2) / numberOfSides;
  31187. for (var i = 0; i < numberOfSides; i++) {
  31188. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31189. angle -= increment;
  31190. }
  31191. return result;
  31192. };
  31193. Polygon.Parse = function (input) {
  31194. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31195. var i, result = [];
  31196. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31197. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31198. }
  31199. return result;
  31200. };
  31201. Polygon.StartingAt = function (x, y) {
  31202. return BABYLON.Path2.StartingAt(x, y);
  31203. };
  31204. return Polygon;
  31205. })();
  31206. BABYLON.Polygon = Polygon;
  31207. var PolygonMeshBuilder = (function () {
  31208. function PolygonMeshBuilder(name, contours, scene) {
  31209. this._points = new PolygonPoints();
  31210. this._outlinepoints = new PolygonPoints();
  31211. this._holes = [];
  31212. if (!("poly2tri" in window)) {
  31213. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31214. }
  31215. this._name = name;
  31216. this._scene = scene;
  31217. var points;
  31218. if (contours instanceof BABYLON.Path2) {
  31219. points = contours.getPoints();
  31220. }
  31221. else {
  31222. points = contours;
  31223. }
  31224. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31225. this._outlinepoints.add(points);
  31226. }
  31227. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31228. this._swctx.addHole(this._points.add(hole));
  31229. var holepoints = new PolygonPoints();
  31230. holepoints.add(hole);
  31231. this._holes.push(holepoints);
  31232. return this;
  31233. };
  31234. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31235. var _this = this;
  31236. if (updatable === void 0) { updatable = false; }
  31237. var result = new BABYLON.Mesh(this._name, this._scene);
  31238. var normals = [];
  31239. var positions = [];
  31240. var uvs = [];
  31241. var bounds = this._points.computeBounds();
  31242. this._points.elements.forEach(function (p) {
  31243. normals.push(0, 1.0, 0);
  31244. positions.push(p.x, 0, p.y);
  31245. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31246. });
  31247. var indices = [];
  31248. this._swctx.triangulate();
  31249. this._swctx.getTriangles().forEach(function (triangle) {
  31250. triangle.getPoints().forEach(function (point) {
  31251. indices.push(point.index);
  31252. });
  31253. });
  31254. if (depth > 0) {
  31255. var positionscount = (positions.length / 3); //get the current pointcount
  31256. this._points.elements.forEach(function (p) {
  31257. normals.push(0, -1.0, 0);
  31258. positions.push(p.x, -depth, p.y);
  31259. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31260. });
  31261. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31262. var p2;
  31263. var poscounter = 0;
  31264. this._swctx.getTriangles().forEach(function (triangle) {
  31265. triangle.getPoints().forEach(function (point) {
  31266. switch (poscounter) {
  31267. case 0:
  31268. p1 = point;
  31269. break;
  31270. case 1:
  31271. p2 = point;
  31272. break;
  31273. case 2:
  31274. indices.push(point.index + positionscount);
  31275. indices.push(p2.index + positionscount);
  31276. indices.push(p1.index + positionscount);
  31277. poscounter = -1;
  31278. break;
  31279. }
  31280. poscounter++;
  31281. //indices.push((<IndexedVector2>point).index + positionscount);
  31282. });
  31283. });
  31284. //Add the sides
  31285. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31286. this._holes.forEach(function (hole) {
  31287. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31288. });
  31289. }
  31290. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31291. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31292. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31293. result.setIndices(indices);
  31294. return result;
  31295. };
  31296. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31297. var StartIndex = positions.length / 3;
  31298. var ulength = 0;
  31299. for (var i = 0; i < points.elements.length; i++) {
  31300. var p = points.elements[i];
  31301. var p1;
  31302. if ((i + 1) > points.elements.length - 1) {
  31303. p1 = points.elements[0];
  31304. }
  31305. else {
  31306. p1 = points.elements[i + 1];
  31307. }
  31308. positions.push(p.x, 0, p.y);
  31309. positions.push(p.x, -depth, p.y);
  31310. positions.push(p1.x, 0, p1.y);
  31311. positions.push(p1.x, -depth, p1.y);
  31312. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31313. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31314. var v3 = v2.subtract(v1);
  31315. var v4 = new BABYLON.Vector3(0, 1, 0);
  31316. var vn = BABYLON.Vector3.Cross(v3, v4);
  31317. vn = vn.normalize();
  31318. uvs.push(ulength / bounds.width, 0);
  31319. uvs.push(ulength / bounds.width, 1);
  31320. ulength += v3.length();
  31321. uvs.push((ulength / bounds.width), 0);
  31322. uvs.push((ulength / bounds.width), 1);
  31323. if (!flip) {
  31324. normals.push(-vn.x, -vn.y, -vn.z);
  31325. normals.push(-vn.x, -vn.y, -vn.z);
  31326. normals.push(-vn.x, -vn.y, -vn.z);
  31327. normals.push(-vn.x, -vn.y, -vn.z);
  31328. indices.push(StartIndex);
  31329. indices.push(StartIndex + 1);
  31330. indices.push(StartIndex + 2);
  31331. indices.push(StartIndex + 1);
  31332. indices.push(StartIndex + 3);
  31333. indices.push(StartIndex + 2);
  31334. }
  31335. else {
  31336. normals.push(vn.x, vn.y, vn.z);
  31337. normals.push(vn.x, vn.y, vn.z);
  31338. normals.push(vn.x, vn.y, vn.z);
  31339. normals.push(vn.x, vn.y, vn.z);
  31340. indices.push(StartIndex);
  31341. indices.push(StartIndex + 2);
  31342. indices.push(StartIndex + 1);
  31343. indices.push(StartIndex + 1);
  31344. indices.push(StartIndex + 2);
  31345. indices.push(StartIndex + 3);
  31346. }
  31347. StartIndex += 4;
  31348. }
  31349. ;
  31350. };
  31351. return PolygonMeshBuilder;
  31352. })();
  31353. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31354. })(BABYLON || (BABYLON = {}));
  31355. var BABYLON;
  31356. (function (BABYLON) {
  31357. var SimplificationSettings = (function () {
  31358. function SimplificationSettings(quality, distance, optimizeMesh) {
  31359. this.quality = quality;
  31360. this.distance = distance;
  31361. this.optimizeMesh = optimizeMesh;
  31362. }
  31363. return SimplificationSettings;
  31364. })();
  31365. BABYLON.SimplificationSettings = SimplificationSettings;
  31366. var SimplificationQueue = (function () {
  31367. function SimplificationQueue() {
  31368. this.running = false;
  31369. this._simplificationArray = [];
  31370. }
  31371. SimplificationQueue.prototype.addTask = function (task) {
  31372. this._simplificationArray.push(task);
  31373. };
  31374. SimplificationQueue.prototype.executeNext = function () {
  31375. var task = this._simplificationArray.pop();
  31376. if (task) {
  31377. this.running = true;
  31378. this.runSimplification(task);
  31379. }
  31380. else {
  31381. this.running = false;
  31382. }
  31383. };
  31384. SimplificationQueue.prototype.runSimplification = function (task) {
  31385. var _this = this;
  31386. if (task.parallelProcessing) {
  31387. //parallel simplifier
  31388. task.settings.forEach(function (setting) {
  31389. var simplifier = _this.getSimplifier(task);
  31390. simplifier.simplify(setting, function (newMesh) {
  31391. task.mesh.addLODLevel(setting.distance, newMesh);
  31392. newMesh.isVisible = true;
  31393. //check if it is the last
  31394. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31395. //all done, run the success callback.
  31396. task.successCallback();
  31397. }
  31398. _this.executeNext();
  31399. });
  31400. });
  31401. }
  31402. else {
  31403. //single simplifier.
  31404. var simplifier = this.getSimplifier(task);
  31405. var runDecimation = function (setting, callback) {
  31406. simplifier.simplify(setting, function (newMesh) {
  31407. task.mesh.addLODLevel(setting.distance, newMesh);
  31408. newMesh.isVisible = true;
  31409. //run the next quality level
  31410. callback();
  31411. });
  31412. };
  31413. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31414. runDecimation(task.settings[loop.index], function () {
  31415. loop.executeNext();
  31416. });
  31417. }, function () {
  31418. //execution ended, run the success callback.
  31419. if (task.successCallback) {
  31420. task.successCallback();
  31421. }
  31422. _this.executeNext();
  31423. });
  31424. }
  31425. };
  31426. SimplificationQueue.prototype.getSimplifier = function (task) {
  31427. switch (task.simplificationType) {
  31428. case SimplificationType.QUADRATIC:
  31429. default:
  31430. return new QuadraticErrorSimplification(task.mesh);
  31431. }
  31432. };
  31433. return SimplificationQueue;
  31434. })();
  31435. BABYLON.SimplificationQueue = SimplificationQueue;
  31436. /**
  31437. * The implemented types of simplification.
  31438. * At the moment only Quadratic Error Decimation is implemented.
  31439. */
  31440. (function (SimplificationType) {
  31441. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31442. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31443. var SimplificationType = BABYLON.SimplificationType;
  31444. var DecimationTriangle = (function () {
  31445. function DecimationTriangle(vertices) {
  31446. this.vertices = vertices;
  31447. this.error = new Array(4);
  31448. this.deleted = false;
  31449. this.isDirty = false;
  31450. this.deletePending = false;
  31451. this.borderFactor = 0;
  31452. }
  31453. return DecimationTriangle;
  31454. })();
  31455. BABYLON.DecimationTriangle = DecimationTriangle;
  31456. var DecimationVertex = (function () {
  31457. function DecimationVertex(position, id) {
  31458. this.position = position;
  31459. this.id = id;
  31460. this.isBorder = true;
  31461. this.q = new QuadraticMatrix();
  31462. this.triangleCount = 0;
  31463. this.triangleStart = 0;
  31464. this.originalOffsets = [];
  31465. }
  31466. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31467. this.position.copyFrom(newPosition);
  31468. };
  31469. return DecimationVertex;
  31470. })();
  31471. BABYLON.DecimationVertex = DecimationVertex;
  31472. var QuadraticMatrix = (function () {
  31473. function QuadraticMatrix(data) {
  31474. this.data = new Array(10);
  31475. for (var i = 0; i < 10; ++i) {
  31476. if (data && data[i]) {
  31477. this.data[i] = data[i];
  31478. }
  31479. else {
  31480. this.data[i] = 0;
  31481. }
  31482. }
  31483. }
  31484. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31485. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31486. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31487. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31488. return det;
  31489. };
  31490. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31491. for (var i = 0; i < 10; ++i) {
  31492. this.data[i] += matrix.data[i];
  31493. }
  31494. };
  31495. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31496. for (var i = 0; i < 10; ++i) {
  31497. this.data[i] += data[i];
  31498. }
  31499. };
  31500. QuadraticMatrix.prototype.add = function (matrix) {
  31501. var m = new QuadraticMatrix();
  31502. for (var i = 0; i < 10; ++i) {
  31503. m.data[i] = this.data[i] + matrix.data[i];
  31504. }
  31505. return m;
  31506. };
  31507. QuadraticMatrix.FromData = function (a, b, c, d) {
  31508. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31509. };
  31510. //returning an array to avoid garbage collection
  31511. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31512. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31513. };
  31514. return QuadraticMatrix;
  31515. })();
  31516. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31517. var Reference = (function () {
  31518. function Reference(vertexId, triangleId) {
  31519. this.vertexId = vertexId;
  31520. this.triangleId = triangleId;
  31521. }
  31522. return Reference;
  31523. })();
  31524. BABYLON.Reference = Reference;
  31525. /**
  31526. * An implementation of the Quadratic Error simplification algorithm.
  31527. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31528. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31529. * @author RaananW
  31530. */
  31531. var QuadraticErrorSimplification = (function () {
  31532. function QuadraticErrorSimplification(_mesh) {
  31533. this._mesh = _mesh;
  31534. this.initialized = false;
  31535. this.syncIterations = 5000;
  31536. this.aggressiveness = 7;
  31537. this.decimationIterations = 100;
  31538. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31539. }
  31540. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31541. var _this = this;
  31542. this.initDecimatedMesh();
  31543. //iterating through the submeshes array, one after the other.
  31544. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31545. _this.initWithMesh(loop.index, function () {
  31546. _this.runDecimation(settings, loop.index, function () {
  31547. loop.executeNext();
  31548. });
  31549. }, settings.optimizeMesh);
  31550. }, function () {
  31551. setTimeout(function () {
  31552. successCallback(_this._reconstructedMesh);
  31553. }, 0);
  31554. });
  31555. };
  31556. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31557. var _this = this;
  31558. var gCount = 0;
  31559. triangle.vertices.forEach(function (vertex) {
  31560. var count = 0;
  31561. var vPos = vertex.position;
  31562. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31563. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31564. ++count;
  31565. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31566. ++count;
  31567. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31568. ++count;
  31569. if (count > 1) {
  31570. ++gCount;
  31571. }
  31572. ;
  31573. });
  31574. if (gCount > 1) {
  31575. console.log(triangle, gCount);
  31576. }
  31577. return gCount > 1;
  31578. };
  31579. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31580. var _this = this;
  31581. var targetCount = ~~(this.triangles.length * settings.quality);
  31582. var deletedTriangles = 0;
  31583. var triangleCount = this.triangles.length;
  31584. var iterationFunction = function (iteration, callback) {
  31585. setTimeout(function () {
  31586. if (iteration % 5 === 0) {
  31587. _this.updateMesh(iteration === 0);
  31588. }
  31589. for (var i = 0; i < _this.triangles.length; ++i) {
  31590. _this.triangles[i].isDirty = false;
  31591. }
  31592. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31593. var trianglesIterator = function (i) {
  31594. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31595. var t = _this.triangles[tIdx];
  31596. if (!t)
  31597. return;
  31598. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31599. return;
  31600. }
  31601. for (var j = 0; j < 3; ++j) {
  31602. if (t.error[j] < threshold) {
  31603. var deleted0 = [];
  31604. var deleted1 = [];
  31605. var v0 = t.vertices[j];
  31606. var v1 = t.vertices[(j + 1) % 3];
  31607. if (v0.isBorder !== v1.isBorder)
  31608. continue;
  31609. var p = BABYLON.Vector3.Zero();
  31610. var n = BABYLON.Vector3.Zero();
  31611. var uv = BABYLON.Vector2.Zero();
  31612. var color = new BABYLON.Color4(0, 0, 0, 1);
  31613. _this.calculateError(v0, v1, p, n, uv, color);
  31614. var delTr = [];
  31615. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31616. continue;
  31617. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31618. continue;
  31619. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31620. continue;
  31621. var uniqueArray = [];
  31622. delTr.forEach(function (deletedT) {
  31623. if (uniqueArray.indexOf(deletedT) === -1) {
  31624. deletedT.deletePending = true;
  31625. uniqueArray.push(deletedT);
  31626. }
  31627. });
  31628. if (uniqueArray.length % 2 != 0) {
  31629. continue;
  31630. }
  31631. v0.q = v1.q.add(v0.q);
  31632. v0.updatePosition(p);
  31633. var tStart = _this.references.length;
  31634. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31635. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31636. var tCount = _this.references.length - tStart;
  31637. if (tCount <= v0.triangleCount) {
  31638. if (tCount) {
  31639. for (var c = 0; c < tCount; c++) {
  31640. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31641. }
  31642. }
  31643. }
  31644. else {
  31645. v0.triangleStart = tStart;
  31646. }
  31647. v0.triangleCount = tCount;
  31648. break;
  31649. }
  31650. }
  31651. };
  31652. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31653. }, 0);
  31654. };
  31655. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31656. if (triangleCount - deletedTriangles <= targetCount)
  31657. loop.breakLoop();
  31658. else {
  31659. iterationFunction(loop.index, function () {
  31660. loop.executeNext();
  31661. });
  31662. }
  31663. }, function () {
  31664. setTimeout(function () {
  31665. //reconstruct this part of the mesh
  31666. _this.reconstructMesh(submeshIndex);
  31667. successCallback();
  31668. }, 0);
  31669. });
  31670. };
  31671. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31672. var _this = this;
  31673. this.vertices = [];
  31674. this.triangles = [];
  31675. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31676. var indices = this._mesh.getIndices();
  31677. var submesh = this._mesh.subMeshes[submeshIndex];
  31678. var findInVertices = function (positionToSearch) {
  31679. if (optimizeMesh) {
  31680. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31681. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31682. return _this.vertices[ii];
  31683. }
  31684. }
  31685. }
  31686. return null;
  31687. };
  31688. var vertexReferences = [];
  31689. var vertexInit = function (i) {
  31690. var offset = i + submesh.verticesStart;
  31691. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31692. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31693. vertex.originalOffsets.push(offset);
  31694. if (vertex.id == _this.vertices.length) {
  31695. _this.vertices.push(vertex);
  31696. }
  31697. vertexReferences.push(vertex.id);
  31698. };
  31699. //var totalVertices = mesh.getTotalVertices();
  31700. var totalVertices = submesh.verticesCount;
  31701. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31702. var indicesInit = function (i) {
  31703. var offset = (submesh.indexStart / 3) + i;
  31704. var pos = (offset * 3);
  31705. var i0 = indices[pos + 0];
  31706. var i1 = indices[pos + 1];
  31707. var i2 = indices[pos + 2];
  31708. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31709. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31710. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31711. var triangle = new DecimationTriangle([v0, v1, v2]);
  31712. triangle.originalOffset = pos;
  31713. _this.triangles.push(triangle);
  31714. };
  31715. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31716. _this.init(callback);
  31717. });
  31718. });
  31719. };
  31720. QuadraticErrorSimplification.prototype.init = function (callback) {
  31721. var _this = this;
  31722. var triangleInit1 = function (i) {
  31723. var t = _this.triangles[i];
  31724. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31725. for (var j = 0; j < 3; j++) {
  31726. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  31727. }
  31728. };
  31729. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31730. var triangleInit2 = function (i) {
  31731. var t = _this.triangles[i];
  31732. for (var j = 0; j < 3; ++j) {
  31733. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31734. }
  31735. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31736. };
  31737. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31738. _this.initialized = true;
  31739. callback();
  31740. });
  31741. });
  31742. };
  31743. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31744. var newTriangles = [];
  31745. var i;
  31746. for (i = 0; i < this.vertices.length; ++i) {
  31747. this.vertices[i].triangleCount = 0;
  31748. }
  31749. var t;
  31750. var j;
  31751. for (i = 0; i < this.triangles.length; ++i) {
  31752. if (!this.triangles[i].deleted) {
  31753. t = this.triangles[i];
  31754. for (j = 0; j < 3; ++j) {
  31755. t.vertices[j].triangleCount = 1;
  31756. }
  31757. newTriangles.push(t);
  31758. }
  31759. }
  31760. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31761. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31762. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31763. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31764. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31765. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31766. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31767. var vertexCount = 0;
  31768. for (i = 0; i < this.vertices.length; ++i) {
  31769. var vertex = this.vertices[i];
  31770. vertex.id = vertexCount;
  31771. if (vertex.triangleCount) {
  31772. vertex.originalOffsets.forEach(function (originalOffset) {
  31773. newPositionData.push(vertex.position.x);
  31774. newPositionData.push(vertex.position.y);
  31775. newPositionData.push(vertex.position.z);
  31776. newNormalData.push(normalData[originalOffset * 3]);
  31777. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31778. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31779. if (uvs && uvs.length) {
  31780. newUVsData.push(uvs[(originalOffset * 2)]);
  31781. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31782. }
  31783. else if (colorsData && colorsData.length) {
  31784. newColorsData.push(colorsData[(originalOffset * 4)]);
  31785. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31786. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31787. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31788. }
  31789. ++vertexCount;
  31790. });
  31791. }
  31792. }
  31793. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31794. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31795. var submeshesArray = this._reconstructedMesh.subMeshes;
  31796. this._reconstructedMesh.subMeshes = [];
  31797. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31798. var originalIndices = this._mesh.getIndices();
  31799. for (i = 0; i < newTriangles.length; ++i) {
  31800. var t = newTriangles[i];
  31801. //now get the new referencing point for each vertex
  31802. [0, 1, 2].forEach(function (idx) {
  31803. var id = originalIndices[t.originalOffset + idx];
  31804. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31805. if (offset < 0)
  31806. offset = 0;
  31807. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31808. });
  31809. }
  31810. //overwriting the old vertex buffers and indices.
  31811. this._reconstructedMesh.setIndices(newIndicesArray);
  31812. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31813. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31814. if (newUVsData.length > 0)
  31815. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31816. if (newColorsData.length > 0)
  31817. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31818. //create submesh
  31819. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31820. if (submeshIndex > 0) {
  31821. this._reconstructedMesh.subMeshes = [];
  31822. submeshesArray.forEach(function (submesh) {
  31823. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31824. });
  31825. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31826. }
  31827. };
  31828. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31829. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31830. this._reconstructedMesh.material = this._mesh.material;
  31831. this._reconstructedMesh.parent = this._mesh.parent;
  31832. this._reconstructedMesh.isVisible = false;
  31833. };
  31834. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31835. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31836. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31837. if (t.deleted)
  31838. continue;
  31839. var s = this.references[vertex1.triangleStart + i].vertexId;
  31840. var v1 = t.vertices[(s + 1) % 3];
  31841. var v2 = t.vertices[(s + 2) % 3];
  31842. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31843. deletedArray[i] = true;
  31844. delTr.push(t);
  31845. continue;
  31846. }
  31847. var d1 = v1.position.subtract(point);
  31848. d1 = d1.normalize();
  31849. var d2 = v2.position.subtract(point);
  31850. d2 = d2.normalize();
  31851. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31852. return true;
  31853. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31854. deletedArray[i] = false;
  31855. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31856. return true;
  31857. }
  31858. return false;
  31859. };
  31860. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31861. var newDeleted = deletedTriangles;
  31862. for (var i = 0; i < vertex.triangleCount; ++i) {
  31863. var ref = this.references[vertex.triangleStart + i];
  31864. var t = this.triangles[ref.triangleId];
  31865. if (t.deleted)
  31866. continue;
  31867. if (deletedArray[i] && t.deletePending) {
  31868. t.deleted = true;
  31869. newDeleted++;
  31870. continue;
  31871. }
  31872. t.vertices[ref.vertexId] = origVertex;
  31873. t.isDirty = true;
  31874. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31875. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31876. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31877. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31878. this.references.push(ref);
  31879. }
  31880. return newDeleted;
  31881. };
  31882. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31883. for (var i = 0; i < this.vertices.length; ++i) {
  31884. var vCount = [];
  31885. var vId = [];
  31886. var v = this.vertices[i];
  31887. var j;
  31888. for (j = 0; j < v.triangleCount; ++j) {
  31889. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31890. for (var ii = 0; ii < 3; ii++) {
  31891. var ofs = 0;
  31892. var vv = triangle.vertices[ii];
  31893. while (ofs < vCount.length) {
  31894. if (vId[ofs] === vv.id)
  31895. break;
  31896. ++ofs;
  31897. }
  31898. if (ofs === vCount.length) {
  31899. vCount.push(1);
  31900. vId.push(vv.id);
  31901. }
  31902. else {
  31903. vCount[ofs]++;
  31904. }
  31905. }
  31906. }
  31907. for (j = 0; j < vCount.length; ++j) {
  31908. if (vCount[j] === 1) {
  31909. this.vertices[vId[j]].isBorder = true;
  31910. }
  31911. else {
  31912. this.vertices[vId[j]].isBorder = false;
  31913. }
  31914. }
  31915. }
  31916. };
  31917. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31918. if (identifyBorders === void 0) { identifyBorders = false; }
  31919. var i;
  31920. if (!identifyBorders) {
  31921. var newTrianglesVector = [];
  31922. for (i = 0; i < this.triangles.length; ++i) {
  31923. if (!this.triangles[i].deleted) {
  31924. newTrianglesVector.push(this.triangles[i]);
  31925. }
  31926. }
  31927. this.triangles = newTrianglesVector;
  31928. }
  31929. for (i = 0; i < this.vertices.length; ++i) {
  31930. this.vertices[i].triangleCount = 0;
  31931. this.vertices[i].triangleStart = 0;
  31932. }
  31933. var t;
  31934. var j;
  31935. var v;
  31936. for (i = 0; i < this.triangles.length; ++i) {
  31937. t = this.triangles[i];
  31938. for (j = 0; j < 3; ++j) {
  31939. v = t.vertices[j];
  31940. v.triangleCount++;
  31941. }
  31942. }
  31943. var tStart = 0;
  31944. for (i = 0; i < this.vertices.length; ++i) {
  31945. this.vertices[i].triangleStart = tStart;
  31946. tStart += this.vertices[i].triangleCount;
  31947. this.vertices[i].triangleCount = 0;
  31948. }
  31949. var newReferences = new Array(this.triangles.length * 3);
  31950. for (i = 0; i < this.triangles.length; ++i) {
  31951. t = this.triangles[i];
  31952. for (j = 0; j < 3; ++j) {
  31953. v = t.vertices[j];
  31954. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31955. v.triangleCount++;
  31956. }
  31957. }
  31958. this.references = newReferences;
  31959. if (identifyBorders) {
  31960. this.identifyBorder();
  31961. }
  31962. };
  31963. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31964. var x = point.x;
  31965. var y = point.y;
  31966. var z = point.z;
  31967. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  31968. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31969. };
  31970. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31971. var q = vertex1.q.add(vertex2.q);
  31972. var border = vertex1.isBorder && vertex2.isBorder;
  31973. var error = 0;
  31974. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31975. if (qDet !== 0 && !border) {
  31976. if (!pointResult) {
  31977. pointResult = BABYLON.Vector3.Zero();
  31978. }
  31979. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31980. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31981. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31982. error = this.vertexError(q, pointResult);
  31983. }
  31984. else {
  31985. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31986. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31987. var error1 = this.vertexError(q, vertex1.position);
  31988. var error2 = this.vertexError(q, vertex2.position);
  31989. var error3 = this.vertexError(q, p3);
  31990. error = Math.min(error1, error2, error3);
  31991. if (error === error1) {
  31992. if (pointResult) {
  31993. pointResult.copyFrom(vertex1.position);
  31994. }
  31995. }
  31996. else if (error === error2) {
  31997. if (pointResult) {
  31998. pointResult.copyFrom(vertex2.position);
  31999. }
  32000. }
  32001. else {
  32002. if (pointResult) {
  32003. pointResult.copyFrom(p3);
  32004. }
  32005. }
  32006. }
  32007. return error;
  32008. };
  32009. return QuadraticErrorSimplification;
  32010. })();
  32011. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32012. })(BABYLON || (BABYLON = {}));
  32013. var BABYLON;
  32014. (function (BABYLON) {
  32015. var Analyser = (function () {
  32016. function Analyser(scene) {
  32017. this.SMOOTHING = 0.75;
  32018. this.FFT_SIZE = 512;
  32019. this.BARGRAPHAMPLITUDE = 256;
  32020. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32021. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32022. this._scene = scene;
  32023. this._audioEngine = BABYLON.Engine.audioEngine;
  32024. if (this._audioEngine.canUseWebAudio) {
  32025. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32026. this._webAudioAnalyser.minDecibels = -140;
  32027. this._webAudioAnalyser.maxDecibels = 0;
  32028. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32029. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32030. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32031. }
  32032. }
  32033. Analyser.prototype.getFrequencyBinCount = function () {
  32034. if (this._audioEngine.canUseWebAudio) {
  32035. return this._webAudioAnalyser.frequencyBinCount;
  32036. }
  32037. else {
  32038. return 0;
  32039. }
  32040. };
  32041. Analyser.prototype.getByteFrequencyData = function () {
  32042. if (this._audioEngine.canUseWebAudio) {
  32043. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32044. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32045. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32046. }
  32047. return this._byteFreqs;
  32048. };
  32049. Analyser.prototype.getByteTimeDomainData = function () {
  32050. if (this._audioEngine.canUseWebAudio) {
  32051. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32052. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32053. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32054. }
  32055. return this._byteTime;
  32056. };
  32057. Analyser.prototype.getFloatFrequencyData = function () {
  32058. if (this._audioEngine.canUseWebAudio) {
  32059. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32060. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32061. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32062. }
  32063. return this._floatFreqs;
  32064. };
  32065. Analyser.prototype.drawDebugCanvas = function () {
  32066. var _this = this;
  32067. if (this._audioEngine.canUseWebAudio) {
  32068. if (!this._debugCanvas) {
  32069. this._debugCanvas = document.createElement("canvas");
  32070. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32071. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32072. this._debugCanvas.style.position = "absolute";
  32073. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32074. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32075. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32076. document.body.appendChild(this._debugCanvas);
  32077. this._registerFunc = function () {
  32078. _this.drawDebugCanvas();
  32079. };
  32080. this._scene.registerBeforeRender(this._registerFunc);
  32081. }
  32082. if (this._registerFunc) {
  32083. var workingArray = this.getByteFrequencyData();
  32084. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32085. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32086. // Draw the frequency domain chart.
  32087. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32088. var value = workingArray[i];
  32089. var percent = value / this.BARGRAPHAMPLITUDE;
  32090. var height = this.DEBUGCANVASSIZE.height * percent;
  32091. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32092. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32093. var hue = i / this.getFrequencyBinCount() * 360;
  32094. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32095. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32096. }
  32097. }
  32098. }
  32099. };
  32100. Analyser.prototype.stopDebugCanvas = function () {
  32101. if (this._debugCanvas) {
  32102. this._scene.unregisterBeforeRender(this._registerFunc);
  32103. this._registerFunc = null;
  32104. document.body.removeChild(this._debugCanvas);
  32105. this._debugCanvas = null;
  32106. this._debugCanvasContext = null;
  32107. }
  32108. };
  32109. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32110. if (this._audioEngine.canUseWebAudio) {
  32111. inputAudioNode.connect(this._webAudioAnalyser);
  32112. this._webAudioAnalyser.connect(outputAudioNode);
  32113. }
  32114. };
  32115. Analyser.prototype.dispose = function () {
  32116. if (this._audioEngine.canUseWebAudio) {
  32117. this._webAudioAnalyser.disconnect();
  32118. }
  32119. };
  32120. return Analyser;
  32121. })();
  32122. BABYLON.Analyser = Analyser;
  32123. })(BABYLON || (BABYLON = {}));
  32124. var BABYLON;
  32125. (function (BABYLON) {
  32126. var DepthRenderer = (function () {
  32127. function DepthRenderer(scene, type) {
  32128. var _this = this;
  32129. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32130. this._viewMatrix = BABYLON.Matrix.Zero();
  32131. this._projectionMatrix = BABYLON.Matrix.Zero();
  32132. this._transformMatrix = BABYLON.Matrix.Zero();
  32133. this._worldViewProjection = BABYLON.Matrix.Zero();
  32134. this._scene = scene;
  32135. var engine = scene.getEngine();
  32136. // Render target
  32137. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32138. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32139. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32140. this._depthMap.refreshRate = 1;
  32141. this._depthMap.renderParticles = false;
  32142. this._depthMap.renderList = null;
  32143. // set default depth value to 1.0 (far away)
  32144. this._depthMap.onClear = function (engine) {
  32145. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32146. };
  32147. // Custom render function
  32148. var renderSubMesh = function (subMesh) {
  32149. var mesh = subMesh.getRenderingMesh();
  32150. var scene = _this._scene;
  32151. var engine = scene.getEngine();
  32152. // Culling
  32153. engine.setState(subMesh.getMaterial().backFaceCulling);
  32154. // Managing instances
  32155. var batch = mesh._getInstancesRenderList(subMesh._id);
  32156. if (batch.mustReturn) {
  32157. return;
  32158. }
  32159. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32160. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32161. engine.enableEffect(_this._effect);
  32162. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32163. var material = subMesh.getMaterial();
  32164. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32165. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32166. // Alpha test
  32167. if (material && material.needAlphaTesting()) {
  32168. var alphaTexture = material.getAlphaTestTexture();
  32169. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32170. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32171. }
  32172. // Bones
  32173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32174. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32175. }
  32176. // Draw
  32177. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32178. }
  32179. };
  32180. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32181. var index;
  32182. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32183. renderSubMesh(opaqueSubMeshes.data[index]);
  32184. }
  32185. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32186. renderSubMesh(alphaTestSubMeshes.data[index]);
  32187. }
  32188. };
  32189. }
  32190. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32191. var defines = [];
  32192. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32193. var mesh = subMesh.getMesh();
  32194. var scene = mesh.getScene();
  32195. var material = subMesh.getMaterial();
  32196. // Alpha test
  32197. if (material && material.needAlphaTesting()) {
  32198. defines.push("#define ALPHATEST");
  32199. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32200. attribs.push(BABYLON.VertexBuffer.UVKind);
  32201. defines.push("#define UV1");
  32202. }
  32203. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32204. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32205. defines.push("#define UV2");
  32206. }
  32207. }
  32208. // Bones
  32209. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32210. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32211. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32212. defines.push("#define BONES");
  32213. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32214. }
  32215. // Instances
  32216. if (useInstances) {
  32217. defines.push("#define INSTANCES");
  32218. attribs.push("world0");
  32219. attribs.push("world1");
  32220. attribs.push("world2");
  32221. attribs.push("world3");
  32222. }
  32223. // Get correct effect
  32224. var join = defines.join("\n");
  32225. if (this._cachedDefines !== join) {
  32226. this._cachedDefines = join;
  32227. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32228. }
  32229. return this._effect.isReady();
  32230. };
  32231. DepthRenderer.prototype.getDepthMap = function () {
  32232. return this._depthMap;
  32233. };
  32234. // Methods
  32235. DepthRenderer.prototype.dispose = function () {
  32236. this._depthMap.dispose();
  32237. };
  32238. return DepthRenderer;
  32239. })();
  32240. BABYLON.DepthRenderer = DepthRenderer;
  32241. })(BABYLON || (BABYLON = {}));
  32242. var BABYLON;
  32243. (function (BABYLON) {
  32244. var SSAORenderingPipeline = (function (_super) {
  32245. __extends(SSAORenderingPipeline, _super);
  32246. /**
  32247. * @constructor
  32248. * @param {string} name - The rendering pipeline name
  32249. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32250. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  32251. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32252. */
  32253. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32254. var _this = this;
  32255. _super.call(this, scene.getEngine(), name);
  32256. // Members
  32257. /**
  32258. * The PassPostProcess id in the pipeline that contains the original scene color
  32259. * @type {string}
  32260. */
  32261. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32262. /**
  32263. * The SSAO PostProcess id in the pipeline
  32264. * @type {string}
  32265. */
  32266. this.SSAORenderEffect = "SSAORenderEffect";
  32267. /**
  32268. * The horizontal blur PostProcess id in the pipeline
  32269. * @type {string}
  32270. */
  32271. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32272. /**
  32273. * The vertical blur PostProcess id in the pipeline
  32274. * @type {string}
  32275. */
  32276. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32277. /**
  32278. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32279. * @type {string}
  32280. */
  32281. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32282. /**
  32283. * The output strength of the SSAO post-process. Default value is 1.0.
  32284. * @type {number}
  32285. */
  32286. this.totalStrength = 1.0;
  32287. /**
  32288. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32289. * @type {number}
  32290. */
  32291. this.radius = 0.0002;
  32292. /**
  32293. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32294. * Must not be equal to fallOff and superior to fallOff.
  32295. * Default value is 0.0075
  32296. * @type {number}
  32297. */
  32298. this.area = 0.0075;
  32299. /**
  32300. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32301. * Must not be equal to area and inferior to area.
  32302. * Default value is 0.0002
  32303. * @type {number}
  32304. */
  32305. this.fallOff = 0.0002;
  32306. this._firstUpdate = true;
  32307. this._scene = scene;
  32308. // Set up assets
  32309. this._createRandomTexture();
  32310. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32311. var ssaoRatio = ratio.ssaoRatio || ratio;
  32312. var combineRatio = ratio.combineRatio || ratio;
  32313. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32314. this._createSSAOPostProcess(ssaoRatio);
  32315. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32316. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32317. this._createSSAOCombinePostProcess(combineRatio);
  32318. // Set up pipeline
  32319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32323. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32324. // Finish
  32325. scene.postProcessRenderPipelineManager.addPipeline(this);
  32326. if (cameras)
  32327. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32328. }
  32329. // Public Methods
  32330. /**
  32331. * Returns the horizontal blur PostProcess
  32332. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32333. */
  32334. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32335. return this._blurHPostProcess;
  32336. };
  32337. /**
  32338. * Returns the vertical blur PostProcess
  32339. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32340. */
  32341. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32342. return this._blurVPostProcess;
  32343. };
  32344. /**
  32345. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32346. */
  32347. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32348. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32349. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32350. this._originalColorPostProcess = undefined;
  32351. this._ssaoPostProcess = undefined;
  32352. this._blurHPostProcess = undefined;
  32353. this._blurVPostProcess = undefined;
  32354. this._ssaoCombinePostProcess = undefined;
  32355. this._randomTexture.dispose();
  32356. if (disableDepthRender)
  32357. this._scene.disableDepthRenderer();
  32358. };
  32359. // Private Methods
  32360. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32361. var _this = this;
  32362. var sampleSphere = [
  32363. 0.5381, 0.1856, -0.4319,
  32364. 0.1379, 0.2486, 0.4430,
  32365. 0.3371, 0.5679, -0.0057,
  32366. -0.6999, -0.0451, -0.0019,
  32367. 0.0689, -0.1598, -0.8547,
  32368. 0.0560, 0.0069, -0.1843,
  32369. -0.0146, 0.1402, 0.0762,
  32370. 0.0100, -0.1924, -0.0344,
  32371. -0.3577, -0.5301, -0.4358,
  32372. -0.3169, 0.1063, 0.0158,
  32373. 0.0103, -0.5869, 0.0046,
  32374. -0.0897, -0.4940, 0.3287,
  32375. 0.7119, -0.0154, -0.0918,
  32376. -0.0533, 0.0596, -0.5411,
  32377. 0.0352, -0.0631, 0.5460,
  32378. -0.4776, 0.2847, -0.0271
  32379. ];
  32380. var samplesFactor = 1.0 / 16.0;
  32381. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32382. this._ssaoPostProcess.onApply = function (effect) {
  32383. if (_this._firstUpdate) {
  32384. effect.setArray3("sampleSphere", sampleSphere);
  32385. effect.setFloat("samplesFactor", samplesFactor);
  32386. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32387. _this._firstUpdate = false;
  32388. }
  32389. effect.setFloat("totalStrength", _this.totalStrength);
  32390. effect.setFloat("radius", _this.radius);
  32391. effect.setFloat("area", _this.area);
  32392. effect.setFloat("fallOff", _this.fallOff);
  32393. effect.setTexture("textureSampler", _this._depthTexture);
  32394. effect.setTexture("randomSampler", _this._randomTexture);
  32395. };
  32396. };
  32397. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32398. var _this = this;
  32399. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32400. this._ssaoCombinePostProcess.onApply = function (effect) {
  32401. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32402. };
  32403. };
  32404. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32405. var size = 512;
  32406. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32407. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32408. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32409. var context = this._randomTexture.getContext();
  32410. var rand = function (min, max) {
  32411. return Math.random() * (max - min) + min;
  32412. };
  32413. for (var x = 0; x < size; x++) {
  32414. for (var y = 0; y < size; y++) {
  32415. var randVector = BABYLON.Vector3.Zero();
  32416. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32417. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32418. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32419. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32420. context.fillRect(x, y, 1, 1);
  32421. }
  32422. }
  32423. this._randomTexture.update(false);
  32424. };
  32425. return SSAORenderingPipeline;
  32426. })(BABYLON.PostProcessRenderPipeline);
  32427. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32428. })(BABYLON || (BABYLON = {}));
  32429. var BABYLON;
  32430. (function (BABYLON) {
  32431. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32432. var VolumetricLightScatteringPostProcess = (function (_super) {
  32433. __extends(VolumetricLightScatteringPostProcess, _super);
  32434. /**
  32435. * @constructor
  32436. * @param {string} name - The post-process name
  32437. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32438. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32439. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32440. * @param {number} samples - The post-process quality, default 100
  32441. * @param {number} samplingMode - The post-process filtering mode
  32442. * @param {BABYLON.Engine} engine - The babylon engine
  32443. * @param {boolean} reusable - If the post-process is reusable
  32444. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32445. */
  32446. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32447. var _this = this;
  32448. if (samples === void 0) { samples = 100; }
  32449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32450. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32451. this._screenCoordinates = BABYLON.Vector2.Zero();
  32452. /**
  32453. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32454. * @type {boolean}
  32455. */
  32456. this.useCustomMeshPosition = false;
  32457. /**
  32458. * If the post-process should inverse the light scattering direction
  32459. * @type {boolean}
  32460. */
  32461. this.invert = true;
  32462. /**
  32463. * Set to true to use the diffuseColor instead of the diffuseTexture
  32464. * @type {boolean}
  32465. */
  32466. this.useDiffuseColor = false;
  32467. /**
  32468. * Array containing the excluded meshes not rendered in the internal pass
  32469. */
  32470. this.excludedMeshes = new Array();
  32471. /**
  32472. * Controls the overall intensity of the post-process
  32473. * @type {number}
  32474. */
  32475. this.exposure = 0.3;
  32476. /**
  32477. * Dissipates each sample's contribution in range [0, 1]
  32478. * @type {number}
  32479. */
  32480. this.decay = 0.96815;
  32481. /**
  32482. * Controls the overall intensity of each sample
  32483. * @type {number}
  32484. */
  32485. this.weight = 0.58767;
  32486. /**
  32487. * Controls the density of each sample
  32488. * @type {number}
  32489. */
  32490. this.density = 0.926;
  32491. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32492. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32493. // Configure mesh
  32494. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32495. // Configure
  32496. this._createPass(scene, ratio.passRatio || ratio);
  32497. this.onApply = function (effect) {
  32498. _this._updateMeshScreenCoordinates(scene);
  32499. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32500. effect.setFloat("exposure", _this.exposure);
  32501. effect.setFloat("decay", _this.decay);
  32502. effect.setFloat("weight", _this.weight);
  32503. effect.setFloat("density", _this.density);
  32504. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32505. };
  32506. }
  32507. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32508. var mesh = subMesh.getMesh();
  32509. var defines = [];
  32510. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32511. var material = subMesh.getMaterial();
  32512. var needUV = false;
  32513. // Render this.mesh as default
  32514. if (mesh === this.mesh) {
  32515. if (this.useDiffuseColor) {
  32516. defines.push("#define DIFFUSE_COLOR_RENDER");
  32517. }
  32518. else if (material) {
  32519. if (material.diffuseTexture !== undefined) {
  32520. defines.push("#define BASIC_RENDER");
  32521. }
  32522. else {
  32523. defines.push("#define DIFFUSE_COLOR_RENDER");
  32524. }
  32525. }
  32526. defines.push("#define NEED_UV");
  32527. needUV = true;
  32528. }
  32529. // Alpha test
  32530. if (material) {
  32531. if (material.needAlphaTesting()) {
  32532. defines.push("#define ALPHATEST");
  32533. }
  32534. if (material.opacityTexture !== undefined) {
  32535. defines.push("#define OPACITY");
  32536. if (material.opacityTexture.getAlphaFromRGB) {
  32537. defines.push("#define OPACITYRGB");
  32538. }
  32539. if (!needUV) {
  32540. defines.push("#define NEED_UV");
  32541. }
  32542. }
  32543. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32544. attribs.push(BABYLON.VertexBuffer.UVKind);
  32545. defines.push("#define UV1");
  32546. }
  32547. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32548. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32549. defines.push("#define UV2");
  32550. }
  32551. }
  32552. // Bones
  32553. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32554. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32555. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32556. defines.push("#define BONES");
  32557. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32558. }
  32559. // Instances
  32560. if (useInstances) {
  32561. defines.push("#define INSTANCES");
  32562. attribs.push("world0");
  32563. attribs.push("world1");
  32564. attribs.push("world2");
  32565. attribs.push("world3");
  32566. }
  32567. // Get correct effect
  32568. var join = defines.join("\n");
  32569. if (this._cachedDefines !== join) {
  32570. this._cachedDefines = join;
  32571. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32572. }
  32573. return this._volumetricLightScatteringPass.isReady();
  32574. };
  32575. /**
  32576. * Sets the new light position for light scattering effect
  32577. * @param {BABYLON.Vector3} The new custom light position
  32578. */
  32579. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32580. this._customMeshPosition = position;
  32581. };
  32582. /**
  32583. * Returns the light position for light scattering effect
  32584. * @return {BABYLON.Vector3} The custom light position
  32585. */
  32586. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32587. return this._customMeshPosition;
  32588. };
  32589. /**
  32590. * Disposes the internal assets and detaches the post-process from the camera
  32591. */
  32592. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32593. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32594. if (rttIndex !== -1) {
  32595. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32596. }
  32597. this._volumetricLightScatteringRTT.dispose();
  32598. _super.prototype.dispose.call(this, camera);
  32599. };
  32600. /**
  32601. * Returns the render target texture used by the post-process
  32602. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32603. */
  32604. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32605. return this._volumetricLightScatteringRTT;
  32606. };
  32607. // Private methods
  32608. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32609. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32610. return true;
  32611. }
  32612. return false;
  32613. };
  32614. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32615. var _this = this;
  32616. var engine = scene.getEngine();
  32617. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32618. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32619. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32620. this._volumetricLightScatteringRTT.renderList = null;
  32621. this._volumetricLightScatteringRTT.renderParticles = false;
  32622. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32623. // Custom render function for submeshes
  32624. var renderSubMesh = function (subMesh) {
  32625. var mesh = subMesh.getRenderingMesh();
  32626. if (_this._meshExcluded(mesh)) {
  32627. return;
  32628. }
  32629. var scene = mesh.getScene();
  32630. var engine = scene.getEngine();
  32631. // Culling
  32632. engine.setState(subMesh.getMaterial().backFaceCulling);
  32633. // Managing instances
  32634. var batch = mesh._getInstancesRenderList(subMesh._id);
  32635. if (batch.mustReturn) {
  32636. return;
  32637. }
  32638. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32639. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32640. engine.enableEffect(_this._volumetricLightScatteringPass);
  32641. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32642. var material = subMesh.getMaterial();
  32643. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32644. // Alpha test
  32645. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32646. var alphaTexture = material.getAlphaTestTexture();
  32647. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32648. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32649. }
  32650. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32651. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32652. if (alphaTexture) {
  32653. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32654. }
  32655. }
  32656. if (material.opacityTexture !== undefined) {
  32657. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32658. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32659. }
  32660. }
  32661. // Bones
  32662. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32663. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32664. }
  32665. // Draw
  32666. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32667. }
  32668. };
  32669. // Render target texture callbacks
  32670. var savedSceneClearColor;
  32671. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32672. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32673. savedSceneClearColor = scene.clearColor;
  32674. scene.clearColor = sceneClearColor;
  32675. };
  32676. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32677. scene.clearColor = savedSceneClearColor;
  32678. };
  32679. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32680. var engine = scene.getEngine();
  32681. var index;
  32682. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32683. renderSubMesh(opaqueSubMeshes.data[index]);
  32684. }
  32685. engine.setAlphaTesting(true);
  32686. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32687. renderSubMesh(alphaTestSubMeshes.data[index]);
  32688. }
  32689. engine.setAlphaTesting(false);
  32690. if (transparentSubMeshes.length) {
  32691. // Sort sub meshes
  32692. for (index = 0; index < transparentSubMeshes.length; index++) {
  32693. var submesh = transparentSubMeshes.data[index];
  32694. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32695. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32696. }
  32697. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32698. sortedArray.sort(function (a, b) {
  32699. // Alpha index first
  32700. if (a._alphaIndex > b._alphaIndex) {
  32701. return 1;
  32702. }
  32703. if (a._alphaIndex < b._alphaIndex) {
  32704. return -1;
  32705. }
  32706. // Then distance to camera
  32707. if (a._distanceToCamera < b._distanceToCamera) {
  32708. return 1;
  32709. }
  32710. if (a._distanceToCamera > b._distanceToCamera) {
  32711. return -1;
  32712. }
  32713. return 0;
  32714. });
  32715. // Render sub meshes
  32716. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32717. for (index = 0; index < sortedArray.length; index++) {
  32718. renderSubMesh(sortedArray[index]);
  32719. }
  32720. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32721. }
  32722. };
  32723. };
  32724. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32725. var transform = scene.getTransformMatrix();
  32726. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32727. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32728. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32729. if (this.invert)
  32730. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32731. };
  32732. // Static methods
  32733. /**
  32734. * Creates a default mesh for the Volumeric Light Scattering post-process
  32735. * @param {string} The mesh name
  32736. * @param {BABYLON.Scene} The scene where to create the mesh
  32737. * @return {BABYLON.Mesh} the default mesh
  32738. */
  32739. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32740. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32741. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32742. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32743. return mesh;
  32744. };
  32745. return VolumetricLightScatteringPostProcess;
  32746. })(BABYLON.PostProcess);
  32747. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32748. })(BABYLON || (BABYLON = {}));
  32749. var BABYLON;
  32750. (function (BABYLON) {
  32751. var LensRenderingPipeline = (function (_super) {
  32752. __extends(LensRenderingPipeline, _super);
  32753. /**
  32754. * @constructor
  32755. *
  32756. * Effect parameters are as follow:
  32757. * {
  32758. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32759. * edge_blur: number; // from 0 to x (1 for realism)
  32760. * distortion: number; // from 0 to x (1 for realism)
  32761. * grain_amount: number; // from 0 to 1
  32762. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32763. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32764. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32765. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32766. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32767. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32768. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32769. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32770. * }
  32771. * Note: if an effect parameter is unset, effect is disabled
  32772. *
  32773. * @param {string} name - The rendering pipeline name
  32774. * @param {object} parameters - An object containing all parameters (see above)
  32775. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32776. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32777. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32778. */
  32779. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32780. var _this = this;
  32781. if (ratio === void 0) { ratio = 1.0; }
  32782. _super.call(this, scene.getEngine(), name);
  32783. // Lens effects can be of the following:
  32784. // - chromatic aberration (slight shift of RGB colors)
  32785. // - blur on the edge of the lens
  32786. // - lens distortion
  32787. // - depth-of-field blur & highlights enhancing
  32788. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32789. // - grain effect (noise or custom texture)
  32790. // Two additional texture samplers are needed:
  32791. // - depth map (for depth-of-field)
  32792. // - grain texture
  32793. /**
  32794. * The chromatic aberration PostProcess id in the pipeline
  32795. * @type {string}
  32796. */
  32797. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32798. /**
  32799. * The highlights enhancing PostProcess id in the pipeline
  32800. * @type {string}
  32801. */
  32802. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32803. /**
  32804. * The depth-of-field PostProcess id in the pipeline
  32805. * @type {string}
  32806. */
  32807. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32808. this._scene = scene;
  32809. // Fetch texture samplers
  32810. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32811. if (parameters.grain_texture) {
  32812. this._grainTexture = parameters.grain_texture;
  32813. }
  32814. else {
  32815. this._createGrainTexture();
  32816. }
  32817. // save parameters
  32818. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32819. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32820. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32821. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32822. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32823. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32824. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32825. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32826. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32827. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32828. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32829. // Create effects
  32830. this._createChromaticAberrationPostProcess(ratio);
  32831. this._createHighlightsPostProcess(ratio);
  32832. this._createDepthOfFieldPostProcess(ratio / 4);
  32833. // Set up pipeline
  32834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32836. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32837. if (this._highlightsGain == -1) {
  32838. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32839. }
  32840. // Finish
  32841. scene.postProcessRenderPipelineManager.addPipeline(this);
  32842. if (cameras) {
  32843. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32844. }
  32845. }
  32846. // public methods (self explanatory)
  32847. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32848. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32849. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32850. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32851. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32852. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32853. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32854. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32855. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32856. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32857. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32858. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32859. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32860. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32861. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32862. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32863. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32864. this._highlightsGain = amount;
  32865. };
  32866. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32867. if (this._highlightsGain == -1) {
  32868. this._highlightsGain = 1.0;
  32869. }
  32870. this._highlightsThreshold = amount;
  32871. };
  32872. LensRenderingPipeline.prototype.disableHighlights = function () {
  32873. this._highlightsGain = -1;
  32874. };
  32875. /**
  32876. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32877. */
  32878. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32879. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32880. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32881. this._chromaticAberrationPostProcess = undefined;
  32882. this._highlightsPostProcess = undefined;
  32883. this._depthOfFieldPostProcess = undefined;
  32884. this._grainTexture.dispose();
  32885. if (disableDepthRender)
  32886. this._scene.disableDepthRenderer();
  32887. };
  32888. // colors shifting and distortion
  32889. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32890. var _this = this;
  32891. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32892. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32893. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32894. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32895. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32896. };
  32897. };
  32898. // highlights enhancing
  32899. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32900. var _this = this;
  32901. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32902. this._highlightsPostProcess.onApply = function (effect) {
  32903. effect.setFloat('gain', _this._highlightsGain);
  32904. effect.setFloat('threshold', _this._highlightsThreshold);
  32905. effect.setBool('pentagon', _this._dofPentagon);
  32906. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32907. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32908. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32909. };
  32910. };
  32911. // colors shifting and distortion
  32912. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32913. var _this = this;
  32914. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32915. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32916. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32917. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32918. this._depthOfFieldPostProcess.onApply = function (effect) {
  32919. effect.setTexture("depthSampler", _this._depthTexture);
  32920. effect.setTexture("grainSampler", _this._grainTexture);
  32921. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32922. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32923. effect.setFloat('grain_amount', _this._grainAmount);
  32924. effect.setBool('blur_noise', _this._blurNoise);
  32925. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32926. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32927. effect.setFloat('distortion', _this._distortion);
  32928. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  32929. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  32930. effect.setFloat('aperture', _this._dofAperture);
  32931. effect.setFloat('darken', _this._dofDarken);
  32932. effect.setFloat('edge_blur', _this._edgeBlur);
  32933. effect.setBool('highlights', (_this._highlightsGain != -1));
  32934. effect.setFloat('near', _this._scene.activeCamera.minZ);
  32935. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  32936. };
  32937. };
  32938. // creates a black and white random noise texture, 512x512
  32939. LensRenderingPipeline.prototype._createGrainTexture = function () {
  32940. var size = 512;
  32941. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32942. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32943. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32944. var context = this._grainTexture.getContext();
  32945. var rand = function (min, max) {
  32946. return Math.random() * (max - min) + min;
  32947. };
  32948. var value;
  32949. for (var x = 0; x < size; x++) {
  32950. for (var y = 0; y < size; y++) {
  32951. value = Math.floor(rand(0.42, 0.58) * 255);
  32952. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  32953. context.fillRect(x, y, 1, 1);
  32954. }
  32955. }
  32956. this._grainTexture.update(false);
  32957. };
  32958. return LensRenderingPipeline;
  32959. })(BABYLON.PostProcessRenderPipeline);
  32960. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  32961. })(BABYLON || (BABYLON = {}));
  32962. //
  32963. // This post-process allows the modification of rendered colors by using
  32964. // a 'look-up table' (LUT). This effect is also called Color Grading.
  32965. //
  32966. // The object needs to be provided an url to a texture containing the color
  32967. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  32968. // Use an image editing software to tweak the LUT to match your needs.
  32969. //
  32970. // For an example of a color LUT, see here:
  32971. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  32972. // For explanations on color grading, see here:
  32973. // http://udn.epicgames.com/Three/ColorGrading.html
  32974. //
  32975. var BABYLON;
  32976. (function (BABYLON) {
  32977. var ColorCorrectionPostProcess = (function (_super) {
  32978. __extends(ColorCorrectionPostProcess, _super);
  32979. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  32980. var _this = this;
  32981. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  32982. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  32983. this._colorTableTexture.anisotropicFilteringLevel = 1;
  32984. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32985. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32986. this.onApply = function (effect) {
  32987. effect.setTexture("colorTable", _this._colorTableTexture);
  32988. };
  32989. }
  32990. return ColorCorrectionPostProcess;
  32991. })(BABYLON.PostProcess);
  32992. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  32993. })(BABYLON || (BABYLON = {}));
  32994. var BABYLON;
  32995. (function (BABYLON) {
  32996. var AnaglyphFreeCamera = (function (_super) {
  32997. __extends(AnaglyphFreeCamera, _super);
  32998. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  32999. _super.call(this, name, position, scene);
  33000. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33001. }
  33002. return AnaglyphFreeCamera;
  33003. })(BABYLON.FreeCamera);
  33004. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33005. var AnaglyphArcRotateCamera = (function (_super) {
  33006. __extends(AnaglyphArcRotateCamera, _super);
  33007. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33008. _super.call(this, name, alpha, beta, radius, target, scene);
  33009. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33010. }
  33011. return AnaglyphArcRotateCamera;
  33012. })(BABYLON.ArcRotateCamera);
  33013. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33014. var AnaglyphGamepadCamera = (function (_super) {
  33015. __extends(AnaglyphGamepadCamera, _super);
  33016. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33017. _super.call(this, name, position, scene);
  33018. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33019. }
  33020. return AnaglyphGamepadCamera;
  33021. })(BABYLON.GamepadCamera);
  33022. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33023. var StereoscopicFreeCamera = (function (_super) {
  33024. __extends(StereoscopicFreeCamera, _super);
  33025. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33026. _super.call(this, name, position, scene);
  33027. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33028. }
  33029. return StereoscopicFreeCamera;
  33030. })(BABYLON.FreeCamera);
  33031. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33032. var StereoscopicArcRotateCamera = (function (_super) {
  33033. __extends(StereoscopicArcRotateCamera, _super);
  33034. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33035. _super.call(this, name, alpha, beta, radius, target, scene);
  33036. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33037. }
  33038. return StereoscopicArcRotateCamera;
  33039. })(BABYLON.ArcRotateCamera);
  33040. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33041. var StereoscopicGamepadCamera = (function (_super) {
  33042. __extends(StereoscopicGamepadCamera, _super);
  33043. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33044. _super.call(this, name, position, scene);
  33045. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33046. }
  33047. return StereoscopicGamepadCamera;
  33048. })(BABYLON.GamepadCamera);
  33049. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33050. })(BABYLON || (BABYLON = {}));
  33051. var BABYLON;
  33052. (function (BABYLON) {
  33053. var HDRRenderingPipeline = (function (_super) {
  33054. __extends(HDRRenderingPipeline, _super);
  33055. /**
  33056. * @constructor
  33057. * @param {string} name - The rendering pipeline name
  33058. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33059. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  33060. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33061. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33062. */
  33063. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33064. var _this = this;
  33065. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33066. _super.call(this, scene.getEngine(), name);
  33067. /**
  33068. * Public members
  33069. */
  33070. // Gaussian Blur
  33071. /**
  33072. * Gaussian blur coefficient
  33073. * @type {number}
  33074. */
  33075. this.gaussCoeff = 0.3;
  33076. /**
  33077. * Gaussian blur mean
  33078. * @type {number}
  33079. */
  33080. this.gaussMean = 1.0;
  33081. /**
  33082. * Gaussian blur standard deviation
  33083. * @type {number}
  33084. */
  33085. this.gaussStandDev = 0.8;
  33086. // HDR
  33087. /**
  33088. * Exposure, controls the overall intensity of the pipeline
  33089. * @type {number}
  33090. */
  33091. this.exposure = 1.0;
  33092. /**
  33093. * Minimum luminance that the post-process can output. Luminance is >= 0
  33094. * @type {number}
  33095. */
  33096. this.minimumLuminance = 1.0;
  33097. /**
  33098. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33099. * @type {number}
  33100. */
  33101. this.maximumLuminance = 1e20;
  33102. /**
  33103. * Increase rate for luminance: eye adaptation speed to dark
  33104. * @type {number}
  33105. */
  33106. this.luminanceIncreaserate = 0.5;
  33107. /**
  33108. * Decrease rate for luminance: eye adaptation speed to bright
  33109. * @type {number}
  33110. */
  33111. this.luminanceDecreaseRate = 0.5;
  33112. // Bright pass
  33113. /**
  33114. * Minimum luminance needed to compute HDR
  33115. * @type {number}
  33116. */
  33117. this.brightThreshold = 0.8;
  33118. this._needUpdate = true;
  33119. this._scene = scene;
  33120. // Bright pass
  33121. this._createBrightPassPostProcess(scene, ratio);
  33122. // Down sample X4
  33123. this._createDownSampleX4PostProcess(scene, ratio);
  33124. // Create gaussian blur post-processes
  33125. this._createGaussianBlurPostProcess(scene, ratio);
  33126. // Texture adder
  33127. this._createTextureAdderPostProcess(scene, ratio);
  33128. // Luminance generator
  33129. this._createLuminanceGeneratorPostProcess(scene);
  33130. // HDR
  33131. this._createHDRPostProcess(scene, ratio);
  33132. // Pass postprocess
  33133. if (originalPostProcess === null) {
  33134. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33135. }
  33136. else {
  33137. this._originalPostProcess = originalPostProcess;
  33138. }
  33139. // Configure pipeline
  33140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33146. var addDownSamplerPostProcess = function (id) {
  33147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33148. };
  33149. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33150. addDownSamplerPostProcess(i);
  33151. }
  33152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33153. // Finish
  33154. scene.postProcessRenderPipelineManager.addPipeline(this);
  33155. if (cameras !== null) {
  33156. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33157. }
  33158. this.update();
  33159. }
  33160. /**
  33161. * Tells the pipeline to update its post-processes
  33162. */
  33163. HDRRenderingPipeline.prototype.update = function () {
  33164. this._needUpdate = true;
  33165. };
  33166. /**
  33167. * Returns the current calculated luminance
  33168. */
  33169. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33170. return this._hdrCurrentLuminance;
  33171. };
  33172. /**
  33173. * Returns the currently drawn luminance
  33174. */
  33175. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33176. return this._hdrOutputLuminance;
  33177. };
  33178. /**
  33179. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33180. */
  33181. HDRRenderingPipeline.prototype.dispose = function () {
  33182. this._originalPostProcess = undefined;
  33183. this._brightPassPostProcess = undefined;
  33184. this._downSampleX4PostProcess = undefined;
  33185. this._guassianBlurHPostProcess = undefined;
  33186. this._guassianBlurVPostProcess = undefined;
  33187. this._textureAdderPostProcess = undefined;
  33188. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33189. this._downSamplePostProcesses[i] = undefined;
  33190. }
  33191. this._hdrPostProcess = undefined;
  33192. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33193. };
  33194. /**
  33195. * Creates the HDR post-process and computes the luminance adaptation
  33196. */
  33197. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33198. var _this = this;
  33199. var hdrLastLuminance = 0.0;
  33200. this._hdrOutputLuminance = -1.0;
  33201. this._hdrCurrentLuminance = 1.0;
  33202. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33203. this._hdrPostProcess.onApply = function (effect) {
  33204. if (_this._hdrOutputLuminance < 0.0) {
  33205. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33206. }
  33207. else {
  33208. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33209. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33210. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33211. }
  33212. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33213. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33214. }
  33215. else {
  33216. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33217. }
  33218. }
  33219. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33220. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33221. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33222. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33223. effect.setFloat("exposure", _this.exposure);
  33224. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33225. _this._needUpdate = false;
  33226. };
  33227. };
  33228. /**
  33229. * Texture Adder post-process
  33230. */
  33231. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33232. var _this = this;
  33233. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33234. this._textureAdderPostProcess.onApply = function (effect) {
  33235. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33236. };
  33237. };
  33238. /**
  33239. * Down sample X4 post-process
  33240. */
  33241. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33242. var _this = this;
  33243. var downSampleX4Offsets = new Array(32);
  33244. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33245. this._downSampleX4PostProcess.onApply = function (effect) {
  33246. if (_this._needUpdate) {
  33247. var id = 0;
  33248. for (var i = -2; i < 2; i++) {
  33249. for (var j = -2; j < 2; j++) {
  33250. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33251. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33252. id += 2;
  33253. }
  33254. }
  33255. }
  33256. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33257. };
  33258. };
  33259. /**
  33260. * Bright pass post-process
  33261. */
  33262. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33263. var _this = this;
  33264. var brightOffsets = new Array(8);
  33265. var brightPassCallback = function (effect) {
  33266. if (_this._needUpdate) {
  33267. var sU = (1.0 / _this._brightPassPostProcess.width);
  33268. var sV = (1.0 / _this._brightPassPostProcess.height);
  33269. brightOffsets[0] = -0.5 * sU;
  33270. brightOffsets[1] = 0.5 * sV;
  33271. brightOffsets[2] = 0.5 * sU;
  33272. brightOffsets[3] = 0.5 * sV;
  33273. brightOffsets[4] = -0.5 * sU;
  33274. brightOffsets[5] = -0.5 * sV;
  33275. brightOffsets[6] = 0.5 * sU;
  33276. brightOffsets[7] = -0.5 * sV;
  33277. }
  33278. effect.setArray2("dsOffsets", brightOffsets);
  33279. effect.setFloat("brightThreshold", _this.brightThreshold);
  33280. };
  33281. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33282. this._brightPassPostProcess.onApply = brightPassCallback;
  33283. };
  33284. /**
  33285. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33286. */
  33287. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33288. var _this = this;
  33289. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33290. var luminanceOffsets = new Array(8);
  33291. var downSampleOffsets = new Array(18);
  33292. var halfDestPixelSize;
  33293. this._downSamplePostProcesses = new Array(lumSteps);
  33294. // Utils for luminance
  33295. var luminanceUpdateSourceOffsets = function (width, height) {
  33296. var sU = (1.0 / width);
  33297. var sV = (1.0 / height);
  33298. luminanceOffsets[0] = -0.5 * sU;
  33299. luminanceOffsets[1] = 0.5 * sV;
  33300. luminanceOffsets[2] = 0.5 * sU;
  33301. luminanceOffsets[3] = 0.5 * sV;
  33302. luminanceOffsets[4] = -0.5 * sU;
  33303. luminanceOffsets[5] = -0.5 * sV;
  33304. luminanceOffsets[6] = 0.5 * sU;
  33305. luminanceOffsets[7] = -0.5 * sV;
  33306. };
  33307. var luminanceUpdateDestOffsets = function (width, height) {
  33308. var id = 0;
  33309. for (var x = -1; x < 2; x++) {
  33310. for (var y = -1; y < 2; y++) {
  33311. downSampleOffsets[id] = (x) / width;
  33312. downSampleOffsets[id + 1] = (y) / height;
  33313. id += 2;
  33314. }
  33315. }
  33316. };
  33317. // Luminance callback
  33318. var luminanceCallback = function (effect) {
  33319. if (_this._needUpdate) {
  33320. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33321. }
  33322. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33323. effect.setArray2("lumOffsets", luminanceOffsets);
  33324. };
  33325. // Down sample callbacks
  33326. var downSampleCallback = function (indice) {
  33327. var i = indice;
  33328. return function (effect) {
  33329. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33330. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33331. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33332. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33333. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33334. effect.setArray2("dsOffsets", downSampleOffsets);
  33335. };
  33336. };
  33337. var downSampleAfterRenderCallback = function (effect) {
  33338. // Unpack result
  33339. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33340. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  33341. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33342. };
  33343. // Create luminance post-process
  33344. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33345. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  33346. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33347. // Create down sample post-processes
  33348. for (var i = lumSteps - 2; i >= 0; i--) {
  33349. var length = Math.pow(3, i);
  33350. ratio = { width: length, height: length };
  33351. var defines = "#define DOWN_SAMPLE\n";
  33352. if (i === 0) {
  33353. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33354. }
  33355. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33356. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33357. if (i === 0) {
  33358. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33359. }
  33360. }
  33361. };
  33362. /**
  33363. * Gaussian blur post-processes. Horizontal and Vertical
  33364. */
  33365. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33366. var _this = this;
  33367. var blurOffsetsW = new Array(9);
  33368. var blurOffsetsH = new Array(9);
  33369. var blurWeights = new Array(9);
  33370. var uniforms = ["blurOffsets", "blurWeights"];
  33371. // Utils for gaussian blur
  33372. var calculateBlurOffsets = function (height) {
  33373. var lastOutputDimensions = {
  33374. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33375. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33376. };
  33377. for (var i = 0; i < 9; i++) {
  33378. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33379. if (height) {
  33380. blurOffsetsH[i] = value;
  33381. }
  33382. else {
  33383. blurOffsetsW[i] = value;
  33384. }
  33385. }
  33386. };
  33387. var calculateWeights = function () {
  33388. var x = 0.0;
  33389. for (var i = 0; i < 9; i++) {
  33390. x = (i - 4.0) / 4.0;
  33391. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  33392. }
  33393. };
  33394. // Callback
  33395. var gaussianBlurCallback = function (height) {
  33396. return function (effect) {
  33397. if (_this._needUpdate) {
  33398. calculateWeights();
  33399. calculateBlurOffsets(height);
  33400. }
  33401. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33402. effect.setArray("blurWeights", blurWeights);
  33403. };
  33404. };
  33405. // Create horizontal gaussian blur post-processes
  33406. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33407. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33408. // Create vertical gaussian blur post-process
  33409. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33410. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33411. };
  33412. // Luminance generator
  33413. HDRRenderingPipeline.LUM_STEPS = 6;
  33414. return HDRRenderingPipeline;
  33415. })(BABYLON.PostProcessRenderPipeline);
  33416. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33417. })(BABYLON || (BABYLON = {}));
  33418. var BABYLON;
  33419. (function (BABYLON) {
  33420. var FaceAdjacencies = (function () {
  33421. function FaceAdjacencies() {
  33422. this.edges = new Array();
  33423. this.edgesConnectedCount = 0;
  33424. }
  33425. return FaceAdjacencies;
  33426. })();
  33427. var EdgesRenderer = (function () {
  33428. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33429. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33430. if (epsilon === void 0) { epsilon = 0.95; }
  33431. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33432. this._linesPositions = new Array();
  33433. this._linesNormals = new Array();
  33434. this._linesIndices = new Array();
  33435. this._buffers = new Array();
  33436. this._checkVerticesInsteadOfIndices = false;
  33437. this._source = source;
  33438. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33439. this._epsilon = epsilon;
  33440. this._prepareRessources();
  33441. this._generateEdgesLines();
  33442. }
  33443. EdgesRenderer.prototype._prepareRessources = function () {
  33444. if (this._lineShader) {
  33445. return;
  33446. }
  33447. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33448. attributes: ["position", "normal"],
  33449. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33450. });
  33451. this._lineShader.disableDepthWrite = true;
  33452. this._lineShader.backFaceCulling = false;
  33453. };
  33454. EdgesRenderer.prototype.dispose = function () {
  33455. this._vb0.dispose();
  33456. this._vb1.dispose();
  33457. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33458. this._lineShader.dispose();
  33459. };
  33460. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33461. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33462. return 0;
  33463. }
  33464. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33465. return 1;
  33466. }
  33467. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33468. return 2;
  33469. }
  33470. return -1;
  33471. };
  33472. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33473. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33474. return 0;
  33475. }
  33476. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33477. return 1;
  33478. }
  33479. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33480. return 2;
  33481. }
  33482. return -1;
  33483. };
  33484. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33485. var needToCreateLine;
  33486. if (edge === undefined) {
  33487. needToCreateLine = true;
  33488. }
  33489. else {
  33490. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33491. needToCreateLine = dotProduct < this._epsilon;
  33492. }
  33493. if (needToCreateLine) {
  33494. var offset = this._linesPositions.length / 3;
  33495. var normal = p0.subtract(p1);
  33496. normal.normalize();
  33497. // Positions
  33498. this._linesPositions.push(p0.x);
  33499. this._linesPositions.push(p0.y);
  33500. this._linesPositions.push(p0.z);
  33501. this._linesPositions.push(p0.x);
  33502. this._linesPositions.push(p0.y);
  33503. this._linesPositions.push(p0.z);
  33504. this._linesPositions.push(p1.x);
  33505. this._linesPositions.push(p1.y);
  33506. this._linesPositions.push(p1.z);
  33507. this._linesPositions.push(p1.x);
  33508. this._linesPositions.push(p1.y);
  33509. this._linesPositions.push(p1.z);
  33510. // Normals
  33511. this._linesNormals.push(p1.x);
  33512. this._linesNormals.push(p1.y);
  33513. this._linesNormals.push(p1.z);
  33514. this._linesNormals.push(-1);
  33515. this._linesNormals.push(p1.x);
  33516. this._linesNormals.push(p1.y);
  33517. this._linesNormals.push(p1.z);
  33518. this._linesNormals.push(1);
  33519. this._linesNormals.push(p0.x);
  33520. this._linesNormals.push(p0.y);
  33521. this._linesNormals.push(p0.z);
  33522. this._linesNormals.push(-1);
  33523. this._linesNormals.push(p0.x);
  33524. this._linesNormals.push(p0.y);
  33525. this._linesNormals.push(p0.z);
  33526. this._linesNormals.push(1);
  33527. // Indices
  33528. this._linesIndices.push(offset);
  33529. this._linesIndices.push(offset + 1);
  33530. this._linesIndices.push(offset + 2);
  33531. this._linesIndices.push(offset);
  33532. this._linesIndices.push(offset + 2);
  33533. this._linesIndices.push(offset + 3);
  33534. }
  33535. };
  33536. EdgesRenderer.prototype._generateEdgesLines = function () {
  33537. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33538. var indices = this._source.getIndices();
  33539. // First let's find adjacencies
  33540. var adjacencies = new Array();
  33541. var faceNormals = new Array();
  33542. var index;
  33543. var faceAdjacencies;
  33544. // Prepare faces
  33545. for (index = 0; index < indices.length; index += 3) {
  33546. faceAdjacencies = new FaceAdjacencies();
  33547. var p0Index = indices[index];
  33548. var p1Index = indices[index + 1];
  33549. var p2Index = indices[index + 2];
  33550. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33551. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33552. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33553. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33554. faceNormal.normalize();
  33555. faceNormals.push(faceNormal);
  33556. adjacencies.push(faceAdjacencies);
  33557. }
  33558. // Scan
  33559. for (index = 0; index < adjacencies.length; index++) {
  33560. faceAdjacencies = adjacencies[index];
  33561. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33562. var otherFaceAdjacencies = adjacencies[otherIndex];
  33563. if (faceAdjacencies.edgesConnectedCount === 3) {
  33564. break;
  33565. }
  33566. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33567. continue;
  33568. }
  33569. var otherP0 = indices[otherIndex * 3];
  33570. var otherP1 = indices[otherIndex * 3 + 1];
  33571. var otherP2 = indices[otherIndex * 3 + 2];
  33572. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33573. var otherEdgeIndex;
  33574. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33575. continue;
  33576. }
  33577. switch (edgeIndex) {
  33578. case 0:
  33579. if (this._checkVerticesInsteadOfIndices) {
  33580. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33581. }
  33582. else {
  33583. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33584. }
  33585. break;
  33586. case 1:
  33587. if (this._checkVerticesInsteadOfIndices) {
  33588. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33589. }
  33590. else {
  33591. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33592. }
  33593. break;
  33594. case 2:
  33595. if (this._checkVerticesInsteadOfIndices) {
  33596. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33597. }
  33598. else {
  33599. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33600. }
  33601. break;
  33602. }
  33603. if (otherEdgeIndex === -1) {
  33604. continue;
  33605. }
  33606. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33607. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33608. faceAdjacencies.edgesConnectedCount++;
  33609. otherFaceAdjacencies.edgesConnectedCount++;
  33610. if (faceAdjacencies.edgesConnectedCount === 3) {
  33611. break;
  33612. }
  33613. }
  33614. }
  33615. }
  33616. // Create lines
  33617. for (index = 0; index < adjacencies.length; index++) {
  33618. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  33619. var current = adjacencies[index];
  33620. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33621. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33622. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33623. }
  33624. // Merge into a single mesh
  33625. var engine = this._source.getScene().getEngine();
  33626. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33627. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33628. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33629. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33630. this._ib = engine.createIndexBuffer(this._linesIndices);
  33631. this._indicesCount = this._linesIndices.length;
  33632. };
  33633. EdgesRenderer.prototype.render = function () {
  33634. if (!this._lineShader.isReady()) {
  33635. return;
  33636. }
  33637. var scene = this._source.getScene();
  33638. var engine = scene.getEngine();
  33639. this._lineShader._preBind();
  33640. // VBOs
  33641. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33642. scene.resetCachedMaterial();
  33643. this._lineShader.setColor4("color", this._source.edgesColor);
  33644. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33645. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33646. this._lineShader.bind(this._source.getWorldMatrix());
  33647. // Draw order
  33648. engine.draw(true, 0, this._indicesCount);
  33649. this._lineShader.unbind();
  33650. engine.setDepthWrite(true);
  33651. };
  33652. return EdgesRenderer;
  33653. })();
  33654. BABYLON.EdgesRenderer = EdgesRenderer;
  33655. })(BABYLON || (BABYLON = {}));
  33656. var BABYLON;
  33657. (function (BABYLON) {
  33658. (function (TonemappingOperator) {
  33659. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  33660. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  33661. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  33662. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  33663. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  33664. var TonemappingOperator = BABYLON.TonemappingOperator;
  33665. ;
  33666. var TonemapPostProcess = (function (_super) {
  33667. __extends(TonemapPostProcess, _super);
  33668. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  33669. var _this = this;
  33670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33671. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33672. this._operator = operator;
  33673. this._exposureAdjustment = exposureAdjustment;
  33674. var params = ["_ExposureAdjustment"];
  33675. var defines = "#define ";
  33676. if (operator === TonemappingOperator.Hable)
  33677. defines += "HABLE_TONEMAPPING";
  33678. else if (operator === TonemappingOperator.Reinhard)
  33679. defines += "REINHARD_TONEMAPPING";
  33680. else if (operator === TonemappingOperator.HejiDawson)
  33681. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  33682. else if (operator === TonemappingOperator.Photographic)
  33683. defines += "PHOTOGRAPHIC_TONEMAPPING";
  33684. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  33685. this.onApply = function (effect) {
  33686. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  33687. };
  33688. }
  33689. return TonemapPostProcess;
  33690. })(BABYLON.PostProcess);
  33691. BABYLON.TonemapPostProcess = TonemapPostProcess;
  33692. })(BABYLON || (BABYLON = {}));
  33693. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  33694. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(o,n,r){var s,e,a,h=i.Normalize(o),u=i.Normalize(r),l=f.X,m=f.Y,x=0,y=0,c=0,p=0,z=0,M=0,w=0,d=-1,I=0,D=0;t.Tools.WithinEpsilon(u.z,0,t.Engine.Epsilon)?M=1:t.Tools.WithinEpsilon(u.x,0,t.Engine.Epsilon)?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),e.normalize(),a=i.Cross(u,e),a.normalize(),s=i.Cross(h,e),s.normalize(),i.Dot(u,s)<0&&(d=1),D=i.Dot(h,e),D=Math.min(1,Math.max(-1,D)),c=Math.acos(D)*d,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),I++);var S,v;return p=0,z=0,M=0,d=-1,t.Tools.WithinEpsilon(u.z,0,t.Engine.Epsilon)?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new i(p,z,M),S.normalize(),v=i.Cross(S,e),v.normalize(),s=i.Cross(u,S),s.normalize(),i.Dot(e,s)<0&&(d=1),D=i.Dot(u,S),D=Math.min(1,Math.max(-1,D)),y=Math.acos(D)*d,i.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),I++),d=-1,s=i.Cross(l,e),s.normalize(),i.Dot(s,m)<0&&(d=1),D=i.Dot(e,l),D=Math.min(1,Math.max(-1,D)),x=-Math.acos(D)*d,0>D&&2>I&&(x=Math.PI+x),new i(y,x,c)},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.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,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  33695. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33696. module.exports = BABYLON;
  33697. };